﻿using AutoMapper;
using Confluent.Kafka;
using EnumsNET;
using MathNet.Numerics.LinearAlgebra;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;

//using NPOI.SS.Formula;
//using NPOI.SS.Formula.Functions;
using NPOI.XWPF.UserModel;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Information;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Math;
using Org.BouncyCastle.Asn1.Tsp;
using Org.BouncyCastle.Asn1.X509;
//using Quartz.Logging;
using S7.Net;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.IO.Pipelines;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Mail;
using System.Net.NetworkInformation;
using System.Numerics;
using System.Reflection;
using System.Reflection.Metadata;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using VOL.Core.BaseProvider;
using VOL.Core.CacheManager;
using VOL.Core.Configuration;
using VOL.Core.Enums;
using VOL.Core.Extensions;
using VOL.Core.ManageUser;
using VOL.Core.Services;
using VOL.Core.Utilities;
using VOL.Entity.DomainModels;
using VOL.Entity.VM;
using VOL.System.IRepositories;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;
using static NPOI.HSSF.Util.HSSFColor;

namespace VOL.System.Services
{
    public partial class Sys_UserService
    {
        private readonly IHubContext<ChatHub> _hubContext;
        Queue<Action> taskQueue = new Queue<Action>();
        private static readonly object lockObject = new object();
        Dictionary<string, string> taskKeys = new Dictionary<string, string>();
        private Microsoft.AspNetCore.Http.HttpContext _context;
        private ISys_UserRepository _repository;
        private static List<EQU_PLCConfig> eQU_PLCConfigs;
        private static List<INTE_CONFIGURE> eINTE_CONFIGURE;
        [ActivatorUtilitiesConstructor]
        public Sys_UserService(IHttpContextAccessor httpContextAccessor, ISys_UserRepository repository)
           : base(repository)
        {
            _context = httpContextAccessor.HttpContext;
            _repository = repository;


        }
        // static bool isRuning= false;
        WebResponseContent webResponse = new WebResponseContent();
        /// <summary>
        /// WebApi登陆
        /// </summary>
        /// <param name="loginInfo"></param>
        /// <param name="verificationCode"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> Login(LoginInfo loginInfo, bool verificationCode = true)
        {

            string msg = string.Empty;
            //   2020.06.12增加验证码
            IMemoryCache memoryCache = _context.GetService<IMemoryCache>();
            string cacheCode = (memoryCache.Get(loginInfo.UUID) ?? "").ToString();
            if (string.IsNullOrEmpty(cacheCode))
            {
                return webResponse.Error("验证码已失效");
            }
            if (cacheCode.ToLower() != loginInfo.VerificationCode.ToLower())
            {
                memoryCache.Remove(loginInfo.UUID);
                return webResponse.Error("验证码不正确");
            }
            try
            {
                Sys_User user = await repository.FindAsIQueryable(x => x.UserName == loginInfo.UserName)
                    .FirstOrDefaultAsync();

                if (user == null || loginInfo.Password.Trim().EncryptDES(AppSetting.Secret.User) != (user.UserPwd ?? ""))
                    return webResponse.Error(ResponseType.LoginError);

                string token = JwtHelper.IssueJwt(new UserInfo()
                {
                    User_Id = user.User_Id,
                    UserName = user.UserName,
                    Role_Id = user.Role_Id
                });
                user.Token = token;
                webResponse.Data = new { token, userName = user.UserTrueName, img = user.HeadImageUrl };
                repository.Update(user, x => x.Token, true);
                UserContext.Current.LogOut(user.User_Id);

                loginInfo.Password = string.Empty;

                return webResponse.OK(ResponseType.LoginSuccess);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                {
                    throw new Exception(ex.Message + ex.StackTrace);
                }
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {
                memoryCache.Remove(loginInfo.UUID);
                Logger.Info(LoggerType.Login, loginInfo.Serialize(), webResponse.Message, msg);
            }
        }
        /// <summary>
        /// WebApi登陆
        /// </summary>
        /// <param name="loginInfo"></param>
        /// <param name="verificationCode"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> Login(LoginInfo loginInfo)
        {
            string msg = string.Empty;
            //   2020.06.12增加验证码
            IMemoryCache memoryCache = _context.GetService<IMemoryCache>();
            try
            {

                eQU_PLCConfigs = await repository.FindAsync<EQU_PLCConfig>(t => t.EquipmentId != null);
                memoryCache.Set("eQU_PLCConfigs", eQU_PLCConfigs);
                eINTE_CONFIGURE = await repository.FindAsync<INTE_CONFIGURE>(t => t.ConfigureName != null);

                Sys_User user = await repository.FindAsIQueryable(x => x.UserName == loginInfo.UserName)
                    .FirstOrDefaultAsync();

                if (user == null || loginInfo.Password.Trim().EncryptDES(AppSetting.Secret.User) != (user.UserPwd ?? ""))
                    return webResponse.Error(ResponseType.LoginError);

                string token = JwtHelper.IssueJwt(new UserInfo()
                {
                    User_Id = user.User_Id,
                    UserName = user.UserName,
                    Role_Id = user.Role_Id
                });
                user.Token = token;
                webResponse.Data = new { token, userName = user.UserTrueName, img = user.HeadImageUrl };
                repository.Update(user, x => x.Token, true);
                UserContext.Current.LogOut(user.User_Id);

                loginInfo.Password = string.Empty;

                return webResponse.OK(ResponseType.LoginSuccess);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                {
                    throw new Exception(ex.Message + ex.StackTrace);
                }
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {
                if (loginInfo.UUID != null)
                { memoryCache.Remove(loginInfo.UUID); }

                Logger.Info(LoggerType.Login, loginInfo.Serialize(), webResponse.Message, msg);
            }
        }


        /// <summary>
        ///当token将要过期时，提前置换一个新的token
        /// </summary>
        /// <returns></returns>
        public async Task<WebResponseContent> ReplaceToken()
        {
            string error = "";
            UserInfo userInfo = null;
            try
            {
                string requestToken = _context.Request.Headers[AppSetting.TokenHeaderName];
                requestToken = requestToken?.Replace("Bearer ", "");
                if (UserContext.Current.Token != requestToken) return webResponse.Error("Token已失效!");

                if (JwtHelper.IsExp(requestToken)) return webResponse.Error("Token已过期!");

                int userId = UserContext.Current.UserId;
                userInfo = await
                     repository.FindFirstAsync(x => x.User_Id == userId,
                     s => new UserInfo()
                     {
                         User_Id = userId,
                         UserName = s.UserName,
                         UserTrueName = s.UserTrueName,
                         Role_Id = s.Role_Id,
                         RoleName = s.RoleName
                     });

                if (userInfo == null) return webResponse.Error("未查到用户信息!");

                string token = JwtHelper.IssueJwt(userInfo);
                //移除当前缓存
                base.CacheContext.Remove(userId.GetUserIdKey());
                //只更新的token字段
                repository.Update(new Sys_User() { User_Id = userId, Token = token }, x => x.Token, true);
                webResponse.OK(null, token);
            }
            catch (Exception ex)
            {
                error = ex.Message + ex.StackTrace + ex.Source;
                webResponse.Error("token替换出错了..");
            }
            finally
            {
                Logger.Info(LoggerType.ReplaceToeken, ($"用户Id:{userInfo?.User_Id},用户{userInfo?.UserTrueName}")
                    + (webResponse.Status ? "token替换成功" : "token替换失败"), null, error);
            }
            return webResponse;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> ModifyPwd(string oldPwd, string newPwd)
        {
            oldPwd = oldPwd?.Trim();
            newPwd = newPwd?.Trim();
            string message = "";
            try
            {
                if (string.IsNullOrEmpty(oldPwd)) return webResponse.Error("旧密码不能为空");
                if (string.IsNullOrEmpty(newPwd)) return webResponse.Error("新密码不能为空");
                if (newPwd.Length < 6) return webResponse.Error("密码不能少于6位");

                int userId = UserContext.Current.UserId;
                string userCurrentPwd = await base.repository.FindFirstAsync(x => x.User_Id == userId, s => s.UserPwd);

                string _oldPwd = oldPwd.EncryptDES(AppSetting.Secret.User);
                if (_oldPwd != userCurrentPwd) return webResponse.Error("旧密码不正确");

                string _newPwd = newPwd.EncryptDES(AppSetting.Secret.User);
                if (userCurrentPwd == _newPwd) return webResponse.Error("新密码不能与旧密码相同");


                repository.Update(new Sys_User
                {
                    User_Id = userId,
                    UserPwd = _newPwd,
                    LastModifyPwdDate = DateTime.Now
                }, x => new { x.UserPwd, x.LastModifyPwdDate }, true);

                webResponse.OK("密码修改成功");
            }
            catch (Exception ex)
            {
                message = ex.Message;
                webResponse.Error("服务器了点问题,请稍后再试");
            }
            finally
            {
                if (message == "")
                {
                    Logger.OK(LoggerType.ApiModifyPwd, "密码修改成功");
                }
                else
                {
                    Logger.Error(LoggerType.ApiModifyPwd, message);
                }
            }
            return webResponse;
        }
        /// <summary>
        /// 个人中心获取当前用户信息
        /// </summary>
        /// <returns></returns>
        public async Task<WebResponseContent> GetCurrentUserInfo()
        {
            var data = await base.repository
                .FindAsIQueryable(x => x.User_Id == UserContext.Current.UserId)
                .Select(s => new
                {
                    s.UserName,
                    s.UserTrueName,
                    s.Address,
                    s.PhoneNo,
                    s.Email,
                    s.Remark,
                    s.Gender,
                    s.RoleName,
                    s.HeadImageUrl,
                    s.CreateDate
                })
                .FirstOrDefaultAsync();
            return webResponse.OK(null, data);
        }

        /// <summary>
        /// 设置固定排序方式及显示用户过滤
        /// </summary>
        /// <param name="pageData"></param>
        /// <returns></returns>
        public override PageGridData<Sys_User> GetPageData(PageDataOptions pageData)
        {
            int roleId = -1;
            //树形菜单传查询角色下所有用户
            if (pageData.Value != null)
            {
                roleId = pageData.Value.ToString().GetInt();
            }
            QueryRelativeExpression = (IQueryable<Sys_User> queryable) =>
            {
                if (roleId <= 0)
                {
                    if (UserContext.Current.IsSuperAdmin) return queryable;
                    roleId = UserContext.Current.RoleId;
                }

                //查看用户时，只能看下自己角色下的所有用户
                List<int> roleIds = Sys_RoleService
                   .Instance
                   .GetAllChildrenRoleId(roleId);
                roleIds.Add(roleId);
                //判断查询的角色是否越权
                if (roleId != UserContext.Current.RoleId && !roleIds.Contains(roleId))
                {
                    roleId = -999;
                }
                return queryable.Where(x => roleIds.Contains(x.Role_Id));
            };
            return base.GetPageData(pageData);
        }

        /// <summary>
        /// 新建用户，根据实际情况自行处理
        /// </summary>
        /// <param name="saveModel"></param>
        /// <returns></returns>
        public override WebResponseContent Add(SaveModel saveModel)
        {
            saveModel.MainData["RoleName"] = "无";
            base.AddOnExecute = (SaveModel userModel) =>
            {
                int roleId = userModel?.MainData?["Role_Id"].GetInt() ?? 0;
                if (roleId > 0 && !UserContext.Current.IsSuperAdmin)
                {
                    string roleName = GetChildrenName(roleId);
                    if ((roleId == 1) || string.IsNullOrEmpty(roleName))
                        return webResponse.Error("不能选择此角色");
                }
                return webResponse.OK();
            };


            ///生成6位数随机密码
            string pwd = 6.GenerateRandomNumber();
            //在AddOnExecuting之前已经对提交的数据做过验证是否为空
            base.AddOnExecuting = (Sys_User user, object obj) =>
            {
                user.UserName = user.UserName.Trim();
                if (repository.Exists(x => x.UserName == user.UserName))
                    return webResponse.Error("用户名已经被注册");
                user.UserPwd = pwd.EncryptDES(AppSetting.Secret.User);
                //设置默认头像
                return webResponse.OK();
            };

            base.AddOnExecuted = (Sys_User user, object list) =>
            {
                var deptIds = user.DeptIds?.Split(",").Select(s => s.GetGuid()).Where(x => x != null).Select(s => (Guid)s).ToArray();
                SaveDepartment(deptIds, user.User_Id);
                return webResponse.OK($"用户新建成功.帐号{user.UserName}密码{pwd}");
            };
            return base.Add(saveModel); ;
        }

        /// <summary>
        /// 删除用户拦截过滤
        /// 用户被删除后同时清空对应缓存
        /// </summary>
        /// <param name="keys"></param>
        /// <param name="delList"></param>
        /// <returns></returns>
        public override WebResponseContent Del(object[] keys, bool delList = false)
        {
            base.DelOnExecuting = (object[] ids) =>
            {
                if (!UserContext.Current.IsSuperAdmin)
                {
                    int[] userIds = ids.Select(x => Convert.ToInt32(x)).ToArray();
                    //校验只能删除当前角色下能看到的用户
                    var xxx = repository.Find(x => userIds.Contains(x.User_Id));
                    var delUserIds = repository.Find(x => userIds.Contains(x.User_Id), s => new { s.User_Id, s.Role_Id, s.UserTrueName });
                    List<int> roleIds = Sys_RoleService
                       .Instance
                       .GetAllChildrenRoleId(UserContext.Current.RoleId);

                    string[] userNames = delUserIds.Where(x => !roleIds.Contains(x.Role_Id))
                     .Select(s => s.UserTrueName)
                     .ToArray();
                    if (userNames.Count() > 0)
                    {
                        return webResponse.Error($"没有权限删除用户：{string.Join(',', userNames)}");
                    }
                }

                return webResponse.OK();
            };
            base.DelOnExecuted = (object[] userIds) =>
            {
                var objKeys = userIds.Select(x => x.GetInt().GetUserIdKey());
                base.CacheContext.RemoveAll(objKeys);
                return new WebResponseContent() { Status = true };
            };
            return base.Del(keys, delList);
        }

        private string GetChildrenName(int roleId)
        {
            //只能修改当前角色能看到的用户
            string roleName = Sys_RoleService
                .Instance
                .GetAllChildren(UserContext.Current.UserInfo.Role_Id).Where(x => x.Id == roleId)
                .Select(s => s.RoleName).FirstOrDefault();
            return roleName;
        }

        /// <summary>
        /// 修改用户拦截过滤
        /// 
        /// </summary>
        /// <param name="saveModel"></param>
        /// <returns></returns>
        public override WebResponseContent Update(SaveModel saveModel)
        {
            UserInfo userInfo = UserContext.Current.UserInfo;
            saveModel.MainData["RoleName"] = "无";
            //禁止修改用户名
            base.UpdateOnExecute = (SaveModel saveInfo) =>
            {
                if (!UserContext.Current.IsSuperAdmin)
                {
                    int roleId = saveModel.MainData["Role_Id"].GetInt();
                    string roleName = GetChildrenName(roleId);
                    saveInfo.MainData.TryAdd("RoleName", roleName);
                    if (UserContext.IsRoleIdSuperAdmin(userInfo.Role_Id))
                    {
                        return webResponse.OK();
                    }
                    if (string.IsNullOrEmpty(roleName)) return webResponse.Error("不能选择此角色");
                }

                return webResponse.OK();
            };
            base.UpdateOnExecuting = (Sys_User user, object obj1, object obj2, List<object> list) =>
            {
                if (user.User_Id == userInfo.User_Id && user.Role_Id != userInfo.Role_Id)
                    return webResponse.Error("不能修改自己的角色");

                var _user = repository.Find(x => x.User_Id == user.User_Id,
                    s => new { s.UserName, s.UserPwd })
                    .FirstOrDefault();
                user.UserName = _user.UserName;
                //Sys_User实体的UserPwd用户密码字段的属性不是编辑，此处不会修改密码。但防止代码生成器将密码字段的修改成了可编辑造成密码被修改
                user.UserPwd = _user.UserPwd;
                return webResponse.OK();
            };
            //用户信息被修改后，将用户的缓存信息清除
            base.UpdateOnExecuted = (Sys_User user, object obj1, object obj2, List<object> List) =>
            {
                base.CacheContext.Remove(user.User_Id.GetUserIdKey());
                var deptIds = user.DeptIds?.Split(",").Select(s => s.GetGuid()).Where(x => x != null).Select(s => (Guid)s).ToArray();
                SaveDepartment(deptIds, user.User_Id);
                return new WebResponseContent(true);
            };
            return base.Update(saveModel);
        }


        /// <summary>
        /// 保存部门
        /// </summary>
        /// <param name="deptIds"></param>
        /// <param name="userId"></param>
        public void SaveDepartment(Guid[] deptIds, int userId)
        {

            if (userId <= 0)
            {
                return;
            }
            if (deptIds == null)
            {
                deptIds = new Guid[] { };
            }

            //如果需要判断当前角色是否越权，再调用一下获取当前部门下的所有子角色判断即可

            var roles = repository.DbContext.Set<Sys_UserDepartment>().Where(x => x.UserId == userId)
              .Select(s => new { s.DepartmentId, s.Enable, s.Id })
              .ToList();
            //没有设置部门
            if (deptIds.Length == 0 && !roles.Exists(x => x.Enable == 1))
            {
                return;
            }

            UserInfo user = UserContext.Current.UserInfo;
            //新设置的部门
            var add = deptIds.Where(x => !roles.Exists(r => r.DepartmentId == x)).Select(s => new Sys_UserDepartment()
            {
                DepartmentId = s,
                UserId = userId,
                Enable = 1,
                CreateDate = DateTime.Now,
                Creator = user.UserTrueName,
                CreateID = user.User_Id
            }).ToList();

            //删除的部门
            var update = roles.Where(x => !deptIds.Contains(x.DepartmentId) && x.Enable == 1).Select(s => new Sys_UserDepartment()
            {
                Id = s.Id,
                Enable = 0,
                ModifyDate = DateTime.Now,
                Modifier = user.UserTrueName,
                ModifyID = user.User_Id
            }).ToList();

            //之前设置过的部门重新分配 
            update.AddRange(roles.Where(x => deptIds.Contains(x.DepartmentId) && x.Enable != 1).Select(s => new Sys_UserDepartment()
            {
                Id = s.Id,
                Enable = 1,
                ModifyDate = DateTime.Now,
                Modifier = user.UserTrueName,
                ModifyID = user.User_Id
            }).ToList());
            repository.AddRange(add);

            repository.UpdateRange(update, x => new { x.Enable, x.ModifyDate, x.Modifier, x.ModifyID });
            repository.SaveChanges();
        }

        /// <summary>
        /// 导出处理
        /// </summary>
        /// <param name="pageData"></param>
        /// <returns></returns>
        public override WebResponseContent Export(PageDataOptions pageData)
        {
            //限定只能导出当前角色能看到的所有用户
            QueryRelativeExpression = (IQueryable<Sys_User> queryable) =>
            {
                if (UserContext.Current.IsSuperAdmin) return queryable;
                List<int> roleIds = Sys_RoleService
                 .Instance
                 .GetAllChildrenRoleId(UserContext.Current.RoleId);
                return queryable.Where(x => roleIds.Contains(x.Role_Id) || x.User_Id == UserContext.Current.UserId);
            };

            base.ExportOnExecuting = (List<Sys_User> list, List<string> ignoreColumn) =>
            {
                if (!ignoreColumn.Contains("Role_Id"))
                {
                    ignoreColumn.Add("Role_Id");
                }
                if (!ignoreColumn.Contains("RoleName"))
                {
                    ignoreColumn.Remove("RoleName");
                }
                WebResponseContent responseData = new WebResponseContent(true);
                return responseData;
            };
            return base.Export(pageData);
        }

        #region by guoyuguo 2024.9.5
        // <summary>
        /// WebApi登陆
        /// </summary>
        /// <param name="loginInfo"></param>
        /// <param name="verificationCode"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> LoginEqu(LoginInfo loginInfo)
        {
            string msg = string.Empty;
            try
            {
                Sys_User user = await repository.FindAsIQueryable(x => x.UserName == loginInfo.UserName)
                    .FirstOrDefaultAsync();

                if (user == null || loginInfo.Password.Trim().EncryptDES(AppSetting.Secret.User) != (user.UserPwd ?? ""))
                    return webResponse.Error(ResponseType.LoginError);

                string token = JwtHelper.IssueJwt(new UserInfo()
                {
                    User_Id = user.User_Id,
                    UserName = user.UserName,
                    Role_Id = user.Role_Id
                });
                user.Token = token;
                webResponse.Data = new { token, userName = user.UserTrueName, img = user.HeadImageUrl };
                repository.Update(user, x => x.Token, true);
                UserContext.Current.LogOut(user.User_Id);

                loginInfo.Password = string.Empty;

                return webResponse.OK(ResponseType.LoginSuccess);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                {
                    throw new Exception(ex.Message + ex.StackTrace);
                }
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {

                Logger.Info(LoggerType.Login, loginInfo.Serialize(), webResponse.Message, msg);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public WebResponseContent ExePro_MES_Auto_Generate_Task()
        {
            string msg = string.Empty;
            try
            {
                var rs = repository.DbContext.Database.ExecuteSqlRaw("EXECUTE [dbo].[Pro_MES_Auto_Generate_Task]");
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                Logger.Info(LoggerType.Login, "异常", webResponse.Message, msg);
                return webResponse.Error(msg);
                //    return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {

                Logger.Info(LoggerType.Login, "OK", webResponse.Message, msg);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <param name="index"></param>
        /// <param name="separator"></param>
        /// <returns></returns>
        private string SplitEx(string input, int index = 0, string separator = "-")
        {
            return input.Split(separator)[index].ToString();
        }
        /// <summary>
        /// 读取配置信息
        /// </summary>
        /// <param name="configureName">配置名</param>
        /// <returns></returns>
        public INTE_CONFIGURE QueryInteConfigure(string configureName)
        {
            INTE_CONFIGURE inteconfig = null;

            //if (eINTE_CONFIGURE == null)
            //{
            eINTE_CONFIGURE = repository.Find<INTE_CONFIGURE>(t => t.ConfigureName != null).ToList();
            //}
            inteconfig = eINTE_CONFIGURE.Where(t => t.ConfigureName == configureName && t.ConfigureValue == 1)
                .FirstOrDefault();


            return inteconfig;
        }
        /// <summary>
        /// 设置设备坐标
        /// </summary>
        /// <param name="eQU_s"></param>
        private void SetEquXY(List<EQU_EQUIPMENT> eQU_s)
        {
            try
            {
                //IMemoryCache memoryCache = _context.GetService<IMemoryCache>();
                //var li = memoryCache.Get("eQU_PLCConfigs");
                if (eQU_PLCConfigs == null)
                {
                    eQU_PLCConfigs = repository.Find<EQU_PLCConfig>(t => t.EquipmentId != null).ToList();
                }
                if (eINTE_CONFIGURE == null)
                {
                    eINTE_CONFIGURE = repository.Find<INTE_CONFIGURE>(t => t.ConfigureName != null).ToList();
                }

                var inteconfig = QueryInteConfigure("PLC_Read");
                if (inteconfig == null)
                    return;
                if (eQU_PLCConfigs != null)
                {
                    IConfigurationSection section = AppSetting.GetSection("PLC");
                    string ip = section["Ip"];

                    var isConnect = IsIpConnect(ip);
                    if (!isConnect)
                    {
                        return;//new ApiResponse(false, $"{ip}连接不上！");
                    }
                    //float db1RoBotArm = 0;
                    //float db1CarArm = 0;
                    //float db1BigCarArm = 0;
                    var isOpen = PlcHelper.Instance.OpenPlc(CpuType.S71500, 0, 1);
                    //if (isOpen)   //判断是否成功
                    //{
                    //    db1RoBotArm = PlcHelper.Instance.ReadReal(273, 8);
                    //    db1CarArm = PlcHelper.Instance.ReadReal(273, 12);
                    //    db1BigCarArm = PlcHelper.Instance.ReadReal(273, 16);
                    //}
                    //PlcHelper.Instance.ClosePlc(PlcHelper.Instance.Plc);
                    foreach (var item in eQU_s)
                    {
                        var id = item.Id.ToString().ToUpper();
                        var plcMl = eQU_PLCConfigs.FirstOrDefault(t => t.EquipmentId == id);
                        if (plcMl != null)
                        {
                            if (isOpen)
                            {
                                var shareX = PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset);
                                item.CurrentX = (decimal)shareX;
                            }


                        }

                    }

                }
            }
            catch (Exception)
            {


            }
            finally
            {
                PlcHelper.Instance.ClosePlc(PlcHelper.Instance.Plc);
            }


        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="equ_tool"></param>
        /// <param name="currentTool"></param>
        /// <param name="equ_task"></param>
        /// <param name="equ_TASKVM1"></param>
        /// <param name="pROC_PROGRAMs"></param>
        private dynamic SetCurrenToll(EQU_TOOL equ_tool, CurrentTool currentTool, EQU_TASK equ_task, Equ_TASKVM equ_TASKVM1, List<PROC_PROGRAM> pROC_PROGRAMs, EQU_EQUIPMENT equipment)
        {

            if (equ_tool != null)
            {
                if (equ_tool.program_seq == 1)
                {
                    equ_TASKVM1.ToolCommandId = "1";
                }
                else if (equ_tool.program_seq == pROC_PROGRAMs.Count())
                { equ_TASKVM1.ToolCommandId = "3"; }
                else { equ_TASKVM1.ToolCommandId = "2"; }
                currentTool.RealityR = equ_tool.reality_R != null ? equ_tool.reality_R.Value : 0;
                currentTool.RealityKnifeWidth = equ_tool.reality_knife_width != null ? equ_tool.reality_knife_width.Value : 0; ;
                currentTool.RealityPairingLength = equ_tool.reality_pairing_length != null ? equ_tool.reality_pairing_length.Value : 0;
                currentTool.Accuracy = equ_tool.accuracy != null ? equ_tool.accuracy.Value : 0;
                currentTool.Location = equ_tool.location != null ? equ_tool.location.Value : 0;
                
            }
            if (equ_task.TaskCode == "TW0031")//换刀
            {
                currentTool.Location = equipment.Location != null ? (int)equipment.Location.Value : 0;
                currentTool.ZIndex = equipment.ZIndex != null ? (int)equipment.ZIndex.Value : 0;
            }
            return null;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<WebResponseContent> Equ_TaskAutoWork(Equ_TASKVM equ_TASKVM)
        {
            string msg = string.Empty;
            string taskNo = equ_TASKVM.TaskNo;
            var sequence = int.Parse(SplitEx(taskNo, taskNo.Split("-").Length - 1));
            //1.获取任务信息 没有设备执行任务
            var eQU_COM_DEFINITION_TASK = await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(t => t.TaskNo == taskNo && t.ActionEquipmentId == null);
            if (eQU_COM_DEFINITION_TASK == null)
            {
                Logger.Info(LoggerType.Login, "此次执行任务以有设备", webResponse.Message, msg);
                return webResponse.Error("此次执行任务以有设备");
            }
            Guid equipment_Id = Guid.Parse(eQU_COM_DEFINITION_TASK.Equipment_Id.ToString());
            Guid eQUTask_Id = Guid.Parse(eQU_COM_DEFINITION_TASK.EQUTask_Id);
            var equml = await repository.FindAsyncFirst<EQU_EQUIPMENT>(t => t.Id == equipment_Id);
            var plan_work_order = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode);
            var equ_tool = await repository.FindAsyncFirst<EQU_TOOL>(t => t.Identifier.StartsWith(eQU_COM_DEFINITION_TASK.OrderCode) && t.program_seq == sequence);
            var equ_task = await repository.FindAsyncFirst<EQU_TASK>(t => t.EQUTask_Id == eQUTask_Id);
            var pROC_PROGRAMs = await repository.FindAsync<PROC_PROGRAM>(t => t.Identifier == eQU_COM_DEFINITION_TASK.OrderCode);
            var pROC_PROGRAM = pROC_PROGRAMs.Where(t => t.sequence == sequence).FirstOrDefault();// await repository.FindAsyncFirst<PROC_PROGRAM>(t => t.Identifier == eQU_COM_DEFINITION_TASK.OrderCode&&t.sequence== sequence);

            if (equ_tool.location == null)
            {
                Logger.Info(LoggerType.Login, "此次执行刀具没入库", webResponse.Message, msg);
                return webResponse.Error("此次执行刀具没入库");
            }
            try
            {
                //2.设备接收任务 2.1设备待机，2.2设备有任务指令 2.3路径无干涩

                var EQU_COM_DEFINITION_TASKml = repository.Find<EQU_COM_DEFINITION_TASK>(t => t.TaskNo == taskNo).FirstOrDefault();
                var eQU_EQUIPMENTs = repository.Find<EQU_EQUIPMENT>(t => t.EquCommds != null && t.StateCode == 1 && t.EquCommds.Contains(EQU_COM_DEFINITION_TASKml.Command)).ToList();
                if (eQU_EQUIPMENTs.Count == 0)
                {

                    Logger.Info(LoggerType.Login, "此次执行任务无空闲设备", webResponse.Message, msg);
                    return webResponse.Error("此次执行任务无空闲设备");
                }
                Equ_TASKVM equ_TASKVM1 = new Equ_TASKVM();
                equ_TASKVM1.Status = equ_task.Status;// 1;
                equ_TASKVM1.EquipmentCode = equml.EquipmentCode;//设备编号
                equ_TASKVM1.SubPathNo = eQU_COM_DEFINITION_TASK.SubPathNo.ToInt();
                equ_TASKVM1.Command = equ_task.TaskCode;// eQU_COM_DEFINITION_TASK.Command;

                equ_TASKVM1.StartTime = DateTime.Now;
                equ_TASKVM1.Unit = equml.unit == null ? 1 : equml.unit.Value;
                equ_TASKVM1.WorkOrderCode = SplitEx(plan_work_order.OrderCode, 2);//调度id
                equ_TASKVM1.OrderCode = plan_work_order.OrderCode;
                equ_TASKVM1.TaskNo = eQU_COM_DEFINITION_TASK.TaskNo;//调度id
                equ_TASKVM1.DbCode = equ_task.DbCode;
                equ_TASKVM1.toolId = equ_tool != null ? equ_tool.Id.ToString() : "";
                equ_TASKVM1.ProgramName = pROC_PROGRAM != null ? pROC_PROGRAM.program_name : "";
                CurrentTool currentTool = new CurrentTool();
                SetCurrenToll(equ_tool, currentTool, equ_task, equ_TASKVM1, pROC_PROGRAMs, equml);

                equ_TASKVM1.CurrentTool = currentTool;
                webResponse.Data = equ_TASKVM1.Serialize().ToString();
                //  webResponse.ExData = "[" + equ_TASKVM1.Serialize().ToString() + "]";
                WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
                {

                    foreach (var item in eQU_EQUIPMENTs)
                    {
                        EQU_COM_DEFINITION_TASKml.ActionEquipmentId = item.Id.ToString().ToUpper();
                        EQU_COM_DEFINITION_TASKml.Status = ((int)StatusAction.Executing).ToString();// "2";//执行中
                        EQU_COM_DEFINITION_TASKml.ExecuteStart = DateTime.Now;
                        // item.StateCode = 0;// 0：自动运行; 1：待机; 2：正常停机; 3：故障停机; 4：待料;5：满料；
                        var arryTaskCode = item.EquCommds.Split(",").ToArray();
                        int iscount = arryTaskCode.Where(t => t.StartsWith(EQU_COM_DEFINITION_TASKml.Command)).Count();
                        if (iscount > 0)
                        {
                            repository.Update<EQU_EQUIPMENT>(item, true);

                            //执行设备

                            //  item.StateCode = 1;
                            repository.Update<EQU_EQUIPMENT>(item, true);
                        }
                        else
                        {
                            return new WebResponseContent().Error("此次执行任务无设备");
                        }
                    }
                    //更新任务状态
                    EQU_COM_DEFINITION_TASKml.Status = equ_TASKVM.Status;
                    EQU_COM_DEFINITION_TASKml.ExecuteEnd = DateTime.Now;
                    repository.Update<EQU_COM_DEFINITION_TASK>(EQU_COM_DEFINITION_TASKml, true);
                    return webResponse.OK(ResponseType.Success);
                });
                //判断事务是否执行成功
                if (!webResponse1.Status)
                {
                    return new WebResponseContent().Error("返回消息");

                }
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                {
                    throw new Exception(ex.Message + ex.StackTrace);
                }
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {

                Logger.Info(LoggerType.Login, eQU_COM_DEFINITION_TASK.Serialize(), webResponse.Message, msg);
            }
        }
        /// <summary>
        /// 自动工作跳转-多工单多任务
        /// </summary>
        /// <param name="_mapper"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<WebResponseContent> Equ_TaskAutoWorkJumpMulti(IMapper _mapper)
        {
            taskKeys.Clear();

            //var context = VOL.Core.Utilities.HttpContext.Current;
            //var UserIP = context.GetUserIp()?.Replace("::ffff:", "");
            //var ServiceIP = context.Connection.LocalIpAddress.MapToIPv4().ToString() + ":" + context.Connection.LocalPort;
            //var serviceIPSend = QueryInteConfigure("ServiceIP");
            //var serviceIP = "192.168.110.183:8088";
            //if (serviceIPSend != null)
            //{
            //    serviceIP = serviceIPSend.ConfigureParam;
            //}
            //if (ServiceIP != serviceIP)
            //{
            //    return webResponse.Error(UserIP + "____" + ServiceIP);
            //}
            string msgError = string.Empty;
            EQU_COM_DEFINITION_TASK eQU_COM_DEFINITION_TASK = null;
            var iNTE_SHELVES = repository.DbContext.Set<INTE_SHELVES>().ToList();
            List<string> statlist = new List<string>() { "1", "5" };
            //设备使能锁
            List<string> emptyEqusEable = null;// new List<string>() { "JCR_001", "SLK_001",  "FNK_001", "SLL_001" };//SLK_002
            var equsEableLock = QueryInteConfigure("EqusEableLock");
            if (equsEableLock != null)
            {
                emptyEqusEable = equsEableLock.ConfigureParam.Split(",").ToList();
            }

            if (equsEableLock != null)
            {
                var Equs = await repository.FindAsync<EQU_EQUIPMENT>(t => emptyEqusEable.Contains(t.EquipmentCode));
                if (Equs != null)
                {
                    foreach (var itemEquipment in Equs)
                    {
                        if (itemEquipment.IsEnable != true)
                        {
                            Logger.Info(LoggerType.Login, "设备未就绪", webResponse.Message, "设备未就绪");
                            webResponse.Data = $"设备未就绪:" + itemEquipment.EquipmentNameZH; ;
                            return webResponse.Error($"设备未就绪:" + itemEquipment.EquipmentNameZH);
                        }
                    }
                }

            }
            //设备锁
            List<string> emptyEqus = null;// new List<string>() { "JCR_001", "SLK_001",  "FNK_001", "SLL_001" };//SLK_002
            var equsLock = QueryInteConfigure("EqusLock");
            if (equsLock != null)
            {
                emptyEqus = equsLock.ConfigureParam.Split(",").ToList();
            }
            //设备任务锁
            List<string> emptyEqusTasks = null;// new List<string>() TW001,TW002,TW003,TW0031,TW0032,TW004,TW005,TW006,TW007
            var equsTaskLock = QueryInteConfigure("EqusLockTask");
            if (equsTaskLock != null)
            {
                emptyEqusTasks = equsTaskLock.ConfigureParam.Split(",").ToList();
            }
            List<string> cmds = new List<string>() { "TASK001", "TW001" };
            var stateOrder = await repository.FindAsync<EQU_COM_DEFINITION_TASK>(t => t.Status == "2");
            var equ_TaskAutos = await repository.FindAsync<V_PLAN_WORK_ORDER_Action>(t => t.IsActivation == "1" && !stateOrder.Select(t1 => t1.OrderCode).ToArray().Contains(t.OrderCode));
            if (equ_TaskAutos.Count == 0)
            {
                Logger.Info(LoggerType.Login, "无工单", webResponse.Message, "无工单");
                return webResponse.Error("无工单");
            }
            foreach (var equ_TaskAuto in equ_TaskAutos)
            {

                if (msgError != "")
                {
                    msgError = "";
                    //   continue;
                    // return webResponse.Error(msgError);
                }


                //1.获取设备信息 没有设备执行任务
                if (equsLock != null)
                {
                    var Equs = await repository.FindAsync<EQU_EQUIPMENT>(t => emptyEqus.Contains(t.EquipmentCode));
                    if (Equs != null)
                    {
                        foreach (var itemEquipment in Equs)
                        {
                            if (itemEquipment.StateCode != 1)
                            {
                                Logger.Info(LoggerType.Login, "设备正运行", webResponse.Message, "设备正运行");
                                msgError += "设备正运行:" + itemEquipment.EquipmentNameZH;
                                continue;
                            }
                        }
                    }

                }

                var planw = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.OrderCode == equ_TaskAuto.OrderCode && t.IsActivation == "1");
                if (planw != null && planw.processing_machines != "3号机")
                {
                    var orkpieceStorage = QueryInteConfigure("WorkpieceStorage");
                    if (orkpieceStorage != null)
                    {
                        var countcmd = await repository.FindAsync<EQU_COM_DEFINITION_TASK>(t => t.OrderCode == equ_TaskAuto.OrderCode && cmds.Contains(t.Command) && (t.Status == "3" || t.Status == "6"));
                        if (countcmd.Count != 2)
                        {
                            msgError += "工件未入库";
                            Logger.Info(LoggerType.Login, "工件未入库", webResponse.Message, "工件未入库");
                        }
                    }
                }


                var equ_TASKVMList = await repository.FindAsync<EQU_COM_DEFINITION_TASK>(
              t => t.OrderCode == equ_TaskAuto.OrderCode && statlist.Contains(t.Status) && t.ActionSort > 1 && t.Command != "TW001" && t.Command != "TASK001");

                var equ_TASKVM = equ_TASKVMList.OrderBy(t => t.ActionSort).FirstOrDefault();
                if (equ_TASKVM == null)
                {
                    msgError += "无执行任务";
                    Logger.Info(LoggerType.Login, "无执行任务", webResponse.Message, "无执行任务");
                    continue;
                    // return webResponse.Error("无执行任务");
                }
                //栅栏门
                #region
                var equml = await repository.FindAsyncFirst<EQU_EQUIPMENT>(t => t.Description == planw.processing_machines&&t.FenceGate=="1");
                if(equml!=null)
                {
                    Logger.Info(LoggerType.Login, $"设备栅栏门打开【{equml.Description}】", $"设备栅栏门打开【{equml.Description}】", $"设备栅栏门打开【{equml.Description}】");
                    continue;
                }
                #endregion
                //拦截
                #region
                var isconntionArray =new List<bool>();
                var interceptionList = await repository.FindAsync<MANU_PROCESS_INTERCEPTION>(t => t.Status == "1"&&t.Order_Id== equ_TaskAuto.OrderCode);
                var condition = new AndCondition();
                MANU_PROCESS_INTERCEPTION_LOG _mANU_PROCESS_INTERCEPTION_LOG = null;
                foreach (var item in interceptionList)
                {
                    condition
                        .AddCondition(new TextCondition("工序", $"{equ_TASKVM.OperationName}",
                                   ConditionOperator.Equal, item.OperationId))
                        .AddCondition(new TextCondition("工单", $"{equ_TASKVM.OrderCode}",
                                   ConditionOperator.Equal, item.Order_Id));
                    if (interceptionList.Count > 0)
                    {
                        var builder = new ConditionBuilder().SetRoot(condition);
                        var valtree = builder.VisualizeExpressionTree();

                        // 实际拦截逻辑
                        if (builder.Evaluate())
                        {
                            // 执行拦截操作
                            _mANU_PROCESS_INTERCEPTION_LOG = new MANU_PROCESS_INTERCEPTION_LOG();
                            _mANU_PROCESS_INTERCEPTION_LOG.Order_Id = item.Order_Id;
                            _mANU_PROCESS_INTERCEPTION_LOG.OperationId = item.OperationId;
                            _mANU_PROCESS_INTERCEPTION_LOG.Reason = valtree;
                            _mANU_PROCESS_INTERCEPTION_LOG.InterceptRule= item.InterceptRule;
                            _mANU_PROCESS_INTERCEPTION_LOG.InterceptType = item.InterceptType;
                            _mANU_PROCESS_INTERCEPTION_LOG.Status = item.Status;
                            _mANU_PROCESS_INTERCEPTION_LOG.CreateOn = DateTime.Now;
                            _mANU_PROCESS_INTERCEPTION_LOG.CreateBy= UserContext.Current.UserInfo.UserTrueName;
                            _mANU_PROCESS_INTERCEPTION_LOG.Handler= UserContext.Current.UserInfo.UserTrueName;
                            _mANU_PROCESS_INTERCEPTION_LOG.InterceptionTime = DateTime.Now;
                            _mANU_PROCESS_INTERCEPTION_LOG.Level= item.Level;
                            _mANU_PROCESS_INTERCEPTION_LOG.Condition = item.Condition;

                            if (_mANU_PROCESS_INTERCEPTION_LOG != null)
                            {
                                repository.DbContext.Set<MANU_PROCESS_INTERCEPTION_LOG>().Add(_mANU_PROCESS_INTERCEPTION_LOG);
                                repository.DbContext.SaveChanges();
                            }
                            
                            isconntionArray.Add(true);
                            continue;
                            // return webResponse.Error(">>> 触发拦截条件，执行拦截操作! <<<" + Environment.NewLine + valtree);
                            //  Console.WriteLine("\n>>> 触发拦截条件，执行拦截操作! <<<");
                        }
                        else
                        {
                            isconntionArray.Add(false);
                            //  Console.WriteLine("\n>>> 条件未满足，继续执行流程 <<<");

                        }
                    }
                }
                if (isconntionArray.Contains(true)==true)
                {
                    continue;
                }
                   
                
                #endregion

                string msg = string.Empty;
                string taskNo = equ_TASKVM.TaskNo;
                var equ_TASKVM4 = await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(
                    t => t.OrderCode == equ_TaskAuto.OrderCode && t.Status == "4");
                if (equ_TASKVM4 != null)
                {
                    Logger.Info(LoggerType.Login, "执行任务有异常", webResponse.Message, "执行任务有异常");
                    msgError += $"工单【{equ_TaskAuto.OrderCode}】执行任务【{equ_TASKVM4.TaskNo}】有异常";
                    continue;
                    // return webResponse.Error("无执行任务");
                }

                var equ_TASKVMTwo = await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(
                    t => t.OrderCode == equ_TaskAuto.OrderCode && t.Status == "2");
                if (equ_TASKVMTwo != null)
                {
                    Logger.Info(LoggerType.Login, "有执行任务未完成" + equ_TASKVMTwo.TaskNo, webResponse.Message, "有执行任务未完成");
                    msgError += "有执行任务未完成" + equ_TASKVMTwo.TaskNo;
                    continue;
                    // return webResponse.Error("有执行任务未完成");
                }


                if (equsTaskLock != null)
                {
                    var currPlanOrder = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.OrderCode == equ_TASKVM.OrderCode);
                    var countcmdTask = await repository.FindAsync<EQU_COM_DEFINITION_TASK>(t => emptyEqusTasks.Contains(t.Command) && (t.Status == "2"));
                    if (countcmdTask.Count == 0)
                    { }
                    else if (countcmdTask.Count > 0 && countcmdTask.Count < 2)
                    {
                        //msgError += "任务排队中";
                        //Logger.Info(LoggerType.Login, "任务排队中", webResponse.Message, "任务排队中");
                        foreach (var t in countcmdTask)
                        {
                            
                            var otherPlanOrder = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(w => w.OrderCode == t.OrderCode);
                            string pattern = @"\d+"; // 匹配一个或多个数字
                            Match matchCurr = Regex.Match(currPlanOrder.processing_machines, pattern);
                            Match matchOther = Regex.Match(otherPlanOrder.processing_machines, pattern);
                            if (matchCurr.Success && matchOther.Success)
                            {
                                if (matchCurr.Value == matchOther.Value)
                                {
                                    Logger.Info(LoggerType.Login, "【" + taskNo + "】任务排队中", webResponse.Message, "任务排队中");
                                    return webResponse.Error("任务排队中【同一台设备】");
                                }

                                if (Math.Abs(int.Parse(matchCurr.Value) - int.Parse(matchOther.Value)) == 1)
                                {
                                    Logger.Info(LoggerType.Login, "设备与设备有干涩");
                                    return webResponse.Error("设备与设备有干涩");
                                }
                            }




                            if (t.OrderCode == equ_TASKVM.OrderCode && (t.Command == "TW004" || t.Command == "TW003") && (equ_TASKVM.Command == "TW004" || equ_TASKVM.Command == "TW003"))
                            {
                                Logger.Info(LoggerType.Login, "【" + taskNo + "】任务排队中", webResponse.Message, "任务排队中");
                                return webResponse.Error("任务排队中【一个工单同时上料，换刀】");
                            }
                            else if (t.OrderCode != equ_TASKVM.OrderCode && (t.Command == "TW0031") && (equ_TASKVM.Command == "TW003"))//不同工单可以同时 上料 上刀
                            {
                            }
                            else if (t.OrderCode != equ_TASKVM.OrderCode && (t.Command == "TW003") && (equ_TASKVM.Command == "TW0031"))//不同工单可以同时 上料 上刀
                            {
                            }
                            else if (t.OrderCode != equ_TASKVM.OrderCode && (t.Command == "TW004") && (equ_TASKVM.Command == "TW003"))  //不同工单可以同时上料，换刀
                            {
                            }
                            else if (t.OrderCode != equ_TASKVM.OrderCode && (t.Command == "TW003") && (equ_TASKVM.Command == "TW004"))  //不同工单可以同时上料，换刀
                            {
                            }
                            else if (t.OrderCode != equ_TASKVM.OrderCode && (t.Command == "TW0032") && (equ_TASKVM.Command == "TW004"))//不同工单可以同时 测量 换刀
                            {
                            }
                            else if (t.OrderCode != equ_TASKVM.OrderCode && (t.Command == "TW004") && (equ_TASKVM.Command == "TW0032"))//不同工单可以同时 测量 换刀
                            {
                            }
                            else if (t.OrderCode != equ_TASKVM.OrderCode && (t.Command == "TW003201") && (equ_TASKVM.Command == "TW004"))//不同工单可以同时 分中 换刀
                            {
                            }
                            else if (t.OrderCode != equ_TASKVM.OrderCode && (t.Command == "TW004") && (equ_TASKVM.Command == "TW003201"))//不同工单可以同时 分中 换刀
                            {
                            }
                            else if (t.OrderCode != equ_TASKVM.OrderCode && (t.Command == "TW003202") && (equ_TASKVM.Command == "TW004"))//不同工单可以同时 找平 换刀
                            {
                            }
                            else if (t.OrderCode != equ_TASKVM.OrderCode && (t.Command == "TW004") && (equ_TASKVM.Command == "TW003202"))//不同工单可以同时 找平 换刀
                            {
                            }
                            else if (t.OrderCode != equ_TASKVM.OrderCode && (equ_TASKVM.Command == "TW0041"))  //不同工单可以加工
                            {
                            }
                            else
                            {
                                Logger.Info(LoggerType.Login, "【" + taskNo + "】任务排队中", webResponse.Message, "任务排队中");
                                return webResponse.Error("任务排队中");
                            }
                        }
                    }
                    else
                    {
                        Logger.Info(LoggerType.Login, "【" + string.Join(",", countcmdTask.Select(t => t.TaskNo).ToArray()) + "】任务排队中");
                        return webResponse.Error("【" + string.Join(",", countcmdTask.Select(t => t.TaskNo).ToArray()) + "】任务排队中");
                    }
                }
                equ_TASKVM.Status =
                    ((int)StatusAction.Executing).ToString(); // ((int)StatusAction.Completed).ToString();
                var sequence = int.Parse(SplitEx(taskNo, taskNo.Split("-").Length - 1));
                //1.获取任务信息 没有设备执行任务
                eQU_COM_DEFINITION_TASK =
                   await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(t =>
                       t.TaskNo == taskNo && t.ActionEquipmentId == null);
                if (eQU_COM_DEFINITION_TASK == null)
                {
                    msgError += "此次执行任务以有设备";
                    Logger.Info(LoggerType.Login, "此次执行任务以有设备", webResponse.Message, msg);
                    continue;
                    // return webResponse.Error("此次执行任务以有设备");
                }

                //var lastEquComDefinitionTask = await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(t =>
                //    t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode && t.ActionSort ==
                //    (eQU_COM_DEFINITION_TASK.ActionSort - 1));
                var lastEquComDefinitionTask = await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(t =>
                   t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode && t.ActionSort ==
                   (eQU_COM_DEFINITION_TASK.ActionSort - 1));
                Guid equipment_Id = Guid.Parse(eQU_COM_DEFINITION_TASK.Equipment_Id.ToString());
                Guid eQUTask_Id = Guid.Parse(eQU_COM_DEFINITION_TASK.EQUTask_Id);
                var equmlcnc = await repository.FindAsyncFirst<EQU_EQUIPMENT>(t => t.Id == equipment_Id);
                var plan_work_order =
                    await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t =>
                        t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode);
                var orderid = plan_work_order.Order_Id.ToString();
                MANU_EXECUTION manuExecution =
                    await repository.FindAsyncFirst<MANU_EXECUTION>(t => t.Order_Id == orderid);
                var op = await repository.FindAsyncFirst<PROC_OPERATION>(t =>
                    t.Identifier == eQU_COM_DEFINITION_TASK.OperationName);
                MANU_SUMMARY manuSummary =
                    await repository.FindAsyncFirst<MANU_SUMMARY>(t =>
                        t.WorkOrderId == orderid && t.OperationId == op.Identifier);
                var productId = Guid.Parse(plan_work_order.ProductId);
                PROC_MATERIAL piece = repository.Find<PROC_MATERIAL>(t => t.Id == productId)
                    .FirstOrDefault();
                var equ_tool = await repository.FindAsyncFirst<EQU_TOOL>(t =>
                    t.Identifier.StartsWith(eQU_COM_DEFINITION_TASK.OrderCode) && t.program_seq == sequence);
                var equ_task = await repository.FindAsyncFirst<EQU_TASK>(t => t.EQUTask_Id == eQUTask_Id);
                var pROC_PROGRAMs =
                    await repository.FindAsync<PROC_PROGRAM>(t => t.Identifier == eQU_COM_DEFINITION_TASK.OrderCode);
                var pROC_PROGRAM =
                    pROC_PROGRAMs.Where(t => t.sequence == sequence)
                        .FirstOrDefault(); // await repository.FindAsyncFirst<PROC_PROGRAM>(t => t.Identifier == eQU_COM_DEFINITION_TASK.OrderCode&&t.sequence== sequence);
                if (equ_tool != null && equ_tool.location == null)
                {
                    msgError += $"【{eQU_COM_DEFINITION_TASK.TaskNo}】此次执行刀具没入库";
                    Logger.Info(LoggerType.Login, $"【{eQU_COM_DEFINITION_TASK.TaskNo}】此次执行刀具没入库", webResponse.Message, msg);
                    continue;
                    // return webResponse.Error("此次执行刀具没入库");
                }
                if (equ_tool != null && equ_tool.location ==0)
                {
                    msgError += $"【{eQU_COM_DEFINITION_TASK.TaskNo}】此次执行刀具没入库";
                    Logger.Info(LoggerType.Login, $"【{eQU_COM_DEFINITION_TASK.TaskNo}】此次执行刀具没入库", webResponse.Message, msg);
                    continue;
                    // return webResponse.Error("此次执行刀具没入库");
                }
                var equCurrentOrder = repository.Find<EQU_EQUIPMENT>(t => t.Id == Guid.Parse(equ_TASKVM.Equipment_Id.ToString().ToUpper()))
                       .FirstOrDefault();
                if (equCurrentOrder != null)
                {
                    equCurrentOrder.CurrentOrder = equ_TASKVM.OrderCode;
                }
                EQU_COM_DEFINITION_TASK EQU_COM_DEFINITION_TASKml = null;
                try
                {
                    //2.设备接收任务 2.1设备待机，2.2设备有任务指令 2.3路径无干涩

                    EQU_COM_DEFINITION_TASKml = repository.Find<EQU_COM_DEFINITION_TASK>(t => t.TaskNo == taskNo)
                       .FirstOrDefault();
                    var eQU_EQUIPMENTs = repository.Find<EQU_EQUIPMENT>(t =>
                        t.EquCommds != null && t.StateCode == 1 &&
                        t.EquCommds.Contains(EQU_COM_DEFINITION_TASKml.Command)).ToList();
                    if (eQU_EQUIPMENTs.Count == 0)
                    {

                        Logger.Info(LoggerType.Login, "此次执行任务无空闲设备", webResponse.Message, msg);
                        msgError += "此次执行任务无空闲设备";
                        continue;
                        // return webResponse.Error("此次执行任务无空闲设备");
                    }

                    var equ_TASKVM1 = EquTaskvm1(equ_task, equmlcnc, eQU_COM_DEFINITION_TASK, plan_work_order, equ_tool,
                        pROC_PROGRAM, pROC_PROGRAMs, piece);
                    webResponse.Data = equ_TASKVM1.Serialize().ToString();
                    //webResponse.ExData = "[" + equ_TASKVM1.Serialize().ToString() + "]";

                    List<Equ_TaskAutoN> taskAutoNs = new List<Equ_TaskAutoN>();
                    WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
                    {
                        SetEquXY(eQU_EQUIPMENTs);
                        foreach (var item in eQU_EQUIPMENTs)
                        {

                            EquComDefinitionTask(EQU_COM_DEFINITION_TASKml, item, equ_tool, iNTE_SHELVES,
                                ((int)StatusAction.Executing).ToString(), equmlcnc);
                            // item.StateCode = 0; // 0：自动运行; 1：待机; 2：正常停机; 3：故障停机; 4：待料;5：满料；
                            if (EQU_COM_DEFINITION_TASKml.Command == "TW0041")//换刀
                            {
                                repository.Update<EQU_TOOL>(equ_tool, true);
                            }

                            var arryTaskCode = item.EquCommds.Split(",").ToArray();
                            int iscount = arryTaskCode.Where(t => t.StartsWith(EQU_COM_DEFINITION_TASKml.Command))
                                .Count();
                            if (iscount > 0)
                            {
                                repository.Update<EQU_EQUIPMENT>(item, true);

                                //执行设备

                                //  item.StateCode = 1;

                            }
                            else
                            {
                                msgError += "此次执行任务无设备";
                                continue;
                                //return new WebResponseContent().Error("此次执行任务无设备");
                            }
                        }
                        if (msgError != "")
                        {
                            return webResponse.Error(msgError);
                        }
                        //更新任务状态
                        EQU_COM_DEFINITION_TASKml.Status = equ_TASKVM.Status;
                        EQU_COM_DEFINITION_TASKml.ExecuteEnd = DateTime.Now;
                        EQU_COM_DEFINITION_TASKml.Description = "";
                        repository.Update<EQU_COM_DEFINITION_TASK>(EQU_COM_DEFINITION_TASKml, true);
                        ManuSummary(ref manuSummary, piece, orderid, EQU_COM_DEFINITION_TASKml);
                        ManuExecution(ref manuExecution, piece, orderid, EQU_COM_DEFINITION_TASKml,
                            lastEquComDefinitionTask, plan_work_order);
                        PlanWorkOrder(ref plan_work_order, EQU_COM_DEFINITION_TASKml);
                        if (equCurrentOrder != null)
                        {
                            repository.Update<EQU_EQUIPMENT>(equCurrentOrder, true);

                        }
                        if (piece != null && EQU_COM_DEFINITION_TASKml.Command == "TW003")//上料
                        {
                            piece.StorageState = "未入库";
                            piece.SHELVES_Id = null;
                            repository.Update<PROC_MATERIAL>(piece, true);
                        }
                        return webResponse.OK(ResponseType.Success);
                    });
                    //判断事务是否执行成功
                    if (!webResponse1.Status)
                    {
                        if (msgError != "")
                        {
                            return webResponse.Error(msgError);
                        }
                        return new WebResponseContent().Error("返回消息");

                    }


                    if (EQU_COM_DEFINITION_TASKml != null)
                    {
                        EQU_COM_DEFINITION_TASK_RECORD taskRecord = new EQU_COM_DEFINITION_TASK_RECORD();
                        taskRecord.EQUTask_Id = EQU_COM_DEFINITION_TASKml.EQUTask_Id;
                        taskRecord.Equipment_Id = EQU_COM_DEFINITION_TASKml.Equipment_Id;
                        taskRecord.SendLog = webResponse.Data.ToString();
                        taskRecord.ComDefintion_TaskId = EQU_COM_DEFINITION_TASKml.ComDefintion_TaskId.ToString().ToUpper();
                        repository.DbContext.Set<EQU_COM_DEFINITION_TASK_RECORD>().Add(taskRecord);

                        var EQU_COM_DEFINITION_TASKLog = repository.Find<EQU_COM_DEFINITION_TASK>(t => t.TaskNo == taskNo)
                      .FirstOrDefault();
                        if (EQU_COM_DEFINITION_TASKLog != null)
                        {
                            var tASK_LOGs = _mapper.Map<EQU_COM_DEFINITION_TASK_LOG>(EQU_COM_DEFINITION_TASKLog);
                            //   EQU_COM_DEFINITION_TASKLog.Status = "2";
                            repository.DbContext.Set<EQU_COM_DEFINITION_TASK_LOG>().AddRange(tASK_LOGs);
                        }

                        repository.DbContext.SaveChanges();

                    }
                    var taskList = repository.Find<EQU_COM_DEFINITION_TASK>(t => t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode);
                    foreach (var item in taskList)
                    {
                        if (EQU_COM_DEFINITION_TASKml.TaskNo == item.TaskNo)
                        {

                        }
                        else
                        {
                            if (EQU_COM_DEFINITION_TASKml.Command == "TW006")
                            {
                                item.IsCurrentOrderCode = "0";
                            }
                            else
                            {
                                item.IsCurrentOrderCode = "1";
                            }
                            repository.DbContext.Update<EQU_COM_DEFINITION_TASK>(item);
                            repository.DbContext.SaveChanges();
                        }

                    }

                    return webResponse.OK(ResponseType.Success);
                }
                catch (Exception ex)
                {
                    msg = ex.Message + ex.StackTrace;
                    if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                    {
                        throw new Exception(ex.Message + ex.StackTrace);
                    }

                    return webResponse.Error(ResponseType.ServerError);
                }
                finally
                {
                    if (webResponse.Data != null)
                    {
                        if (webResponse.Status == true && EQU_COM_DEFINITION_TASKml != null)
                        {
                            taskQueue.Enqueue(() =>
                            //MQ_Send
                            SendTaskToMQ(equmlcnc, EQU_COM_DEFINITION_TASKml)
                            );

                            while (taskQueue.Count > 0)
                            {
                                Action task = taskQueue.Dequeue();
                                await Task.Run(task); // 在新线程中执行任务，保持主线程继续处理队列中的下一个任务。
                            }
                            //try
                            //{
                            //    Monitor.Enter(lockObject);
                            //    lock (lockObject)
                            //    {
                            //        taskKeys.Add(eQU_COM_DEFINITION_TASK.TaskNo, eQU_COM_DEFINITION_TASK.TaskNo);
                            //    }
                            //    foreach (var key in taskKeys)
                            //    {
                            //        //taskQueue.Enqueue(() =>
                            //        ////MQ_Send
                            //        //SendTaskToMQ(equmlcnc, EQU_COM_DEFINITION_TASKml)
                            //        //);

                            //        //while (taskQueue.Count > 0)
                            //        //{
                            //        //    Action task = taskQueue.Dequeue();
                            //        //    await Task.Run(task); // 在新线程中执行任务，保持主线程继续处理队列中的下一个任务。
                            //        //}
                            //        //MQ_Send
                            //        SendTaskToMQ(equmlcnc, EQU_COM_DEFINITION_TASKml);


                            Logger.Info(LoggerType.Add, eQU_COM_DEFINITION_TASK.Serialize(), webResponse.Message, webResponse.Data.ToString());
                            //        Thread.Sleep(200);
                            //    }

                            //}
                            //finally
                            //{
                            //    Monitor.Exit(lockObject);
                            //}

                        }
                        //  Logger.Info(LoggerType.Login, eQU_COM_DEFINITION_TASK.Serialize(), webResponse.Message, webResponse.Data.ToString());
                    }
                    else
                    {
                        Logger.Info(LoggerType.Login, eQU_COM_DEFINITION_TASK.Serialize(), webResponse.Message, "");
                    }

                }
            }
            if (msgError != "")
            {
                if (msgError != "" && eQU_COM_DEFINITION_TASK != null)
                {
                    eQU_COM_DEFINITION_TASK.Description = msgError;
                    repository.DbContext.Update<EQU_COM_DEFINITION_TASK>(eQU_COM_DEFINITION_TASK);
                    repository.DbContext.SaveChanges();
                }
                return webResponse.Error(msgError);
            }
            return webResponse.OK(ResponseType.Success);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<WebResponseContent> Equ_TaskAutoWorkJump(IMapper _mapper, Equ_TaskAuto equ_TaskAuto)
        {
            var iNTE_SHELVES = repository.DbContext.Set<INTE_SHELVES>().ToList();
            List<string> statlist = new List<string>() { "1", "5" };
            List<string> cmds = new List<string>() { "TASK001", "TW001" };
            var orkpieceStorage = QueryInteConfigure("WorkpieceStorage");
            if (orkpieceStorage != null)
            {
                var countcmd = await repository.FindAsync<EQU_COM_DEFINITION_TASK>(t => t.OrderCode == equ_TaskAuto.OrderCode && cmds.Contains(t.Command) && (t.Status == "3" || t.Status == "6"));
                if (countcmd.Count != 2)
                {

                    Logger.Info(LoggerType.Login, "工件未入库", webResponse.Message, "工件未入库");
                    return webResponse.Error("工件未入库");
                }
            }


            //select top 1 ActionSort, TaskNo,  Status, * from EQU_COM_DEFINITION_TASK where Status in ('1','5') and ActionSort>1;
            var equ_TASKVM = await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(
                t => t.OrderCode == equ_TaskAuto.OrderCode && statlist.Contains(t.Status) && t.ActionSort > 1);
            if (equ_TASKVM == null)
            {
                Logger.Info(LoggerType.Login, "无执行任务", webResponse.Message, "无执行任务");
                return webResponse.Error("无执行任务");
            }

            var equ_TASKVMTwo = await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(
                t => t.OrderCode == equ_TaskAuto.OrderCode && t.Status == "2");
            if (equ_TASKVMTwo != null)
            {
                Logger.Info(LoggerType.Login, "有执行任务未完成" + equ_TASKVMTwo.TaskNo, webResponse.Message, "有执行任务未完成");
                return webResponse.Error("有执行任务未完成");
            }

            string msg = string.Empty;
            string taskNo = equ_TASKVM.TaskNo;
            equ_TASKVM.Status =
                ((int)StatusAction.Executing).ToString(); // ((int)StatusAction.Completed).ToString();
            var sequence = int.Parse(SplitEx(taskNo, taskNo.Split("-").Length - 1));
            //1.获取任务信息 没有设备执行任务
            var eQU_COM_DEFINITION_TASK =
                await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(t =>
                    t.TaskNo == taskNo && t.ActionEquipmentId == null);
            if (eQU_COM_DEFINITION_TASK == null)
            {
                Logger.Info(LoggerType.Login, "此次执行任务以有设备", webResponse.Message, msg);
                return webResponse.Error("此次执行任务以有设备");
            }

            var lastEquComDefinitionTask = await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(t =>
                t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode && t.ActionSort ==
                (eQU_COM_DEFINITION_TASK.ActionSort - 1));
            Guid equipment_Id = Guid.Parse(eQU_COM_DEFINITION_TASK.Equipment_Id.ToString());
            Guid eQUTask_Id = Guid.Parse(eQU_COM_DEFINITION_TASK.EQUTask_Id);
            var equmlcnc = await repository.FindAsyncFirst<EQU_EQUIPMENT>(t => t.Id == equipment_Id);
            var plan_work_order =
                await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t =>
                    t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode);
            var orderid = plan_work_order.Order_Id.ToString();
            MANU_EXECUTION manuExecution =
                await repository.FindAsyncFirst<MANU_EXECUTION>(t => t.Order_Id == orderid);
            var op = await repository.FindAsyncFirst<PROC_OPERATION>(t =>
                t.Identifier == eQU_COM_DEFINITION_TASK.OperationName);
            MANU_SUMMARY manuSummary =
                await repository.FindAsyncFirst<MANU_SUMMARY>(t =>
                    t.WorkOrderId == orderid && t.OperationId == op.Identifier);
            var productId = Guid.Parse(plan_work_order.ProductId);
            PROC_MATERIAL piece = repository.Find<PROC_MATERIAL>(t => t.Id == productId)
                .FirstOrDefault();
            var equ_tool = await repository.FindAsyncFirst<EQU_TOOL>(t =>
                t.Identifier.StartsWith(eQU_COM_DEFINITION_TASK.OrderCode) && t.program_seq == sequence);
            var equ_task = await repository.FindAsyncFirst<EQU_TASK>(t => t.EQUTask_Id == eQUTask_Id);
            var pROC_PROGRAMs =
                await repository.FindAsync<PROC_PROGRAM>(t => t.Identifier == eQU_COM_DEFINITION_TASK.OrderCode);
            var pROC_PROGRAM =
                pROC_PROGRAMs.Where(t => t.sequence == sequence)
                    .FirstOrDefault(); // await repository.FindAsyncFirst<PROC_PROGRAM>(t => t.Identifier == eQU_COM_DEFINITION_TASK.OrderCode&&t.sequence== sequence);
            if (equ_tool != null && equ_tool.location == null)
            {
                Logger.Info(LoggerType.Login, "此次执行刀具没入库", webResponse.Message, msg);
                return webResponse.Error("此次执行刀具没入库");
            }

            try
            {
                //2.设备接收任务 2.1设备待机，2.2设备有任务指令 2.3路径无干涩

                var EQU_COM_DEFINITION_TASKml = repository.Find<EQU_COM_DEFINITION_TASK>(t => t.TaskNo == taskNo)
                    .FirstOrDefault();
                var eQU_EQUIPMENTs = repository.Find<EQU_EQUIPMENT>(t =>
                    t.EquCommds != null && t.StateCode == 1 &&
                    t.EquCommds.Contains(EQU_COM_DEFINITION_TASKml.Command)).ToList();
                if (eQU_EQUIPMENTs.Count == 0)
                {

                    Logger.Info(LoggerType.Login, "此次执行任务无空闲设备", webResponse.Message, msg);
                    return webResponse.Error("此次执行任务无空闲设备");
                }

                var equ_TASKVM1 = EquTaskvm1(equ_task, equmlcnc, eQU_COM_DEFINITION_TASK, plan_work_order, equ_tool,
                    pROC_PROGRAM, pROC_PROGRAMs, piece);
                webResponse.Data = equ_TASKVM1.Serialize().ToString();
                //webResponse.ExData = "[" + equ_TASKVM1.Serialize().ToString() + "]";
                List<Equ_TaskAutoN> taskAutoNs = new List<Equ_TaskAutoN>();
                WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
                {
                    SetEquXY(eQU_EQUIPMENTs);
                    foreach (var item in eQU_EQUIPMENTs)
                    {

                        EquComDefinitionTask(EQU_COM_DEFINITION_TASKml, item, equ_tool, iNTE_SHELVES,
                            ((int)StatusAction.Executing).ToString(), equmlcnc);
                        //  item.StateCode = 0; // 0：自动运行; 1：待机; 2：正常停机; 3：故障停机; 4：待料;5：满料；
                        var arryTaskCode = item.EquCommds.Split(",").ToArray();
                        int iscount = arryTaskCode.Where(t => t.StartsWith(EQU_COM_DEFINITION_TASKml.Command))
                            .Count();
                        if (iscount > 0)
                        {
                            repository.Update<EQU_EQUIPMENT>(item, true);

                            //执行设备

                            //   item.StateCode = 1;
                            repository.Update<EQU_EQUIPMENT>(item, true);
                        }
                        else
                        {
                            return new WebResponseContent().Error("此次执行任务无设备");
                        }
                    }

                    //更新任务状态
                    EQU_COM_DEFINITION_TASKml.Status = equ_TASKVM.Status;
                    EQU_COM_DEFINITION_TASKml.ExecuteEnd = DateTime.Now;
                    repository.Update<EQU_COM_DEFINITION_TASK>(EQU_COM_DEFINITION_TASKml, true);
                    ManuSummary(ref manuSummary, piece, orderid, EQU_COM_DEFINITION_TASKml);
                    ManuExecution(ref manuExecution, piece, orderid, EQU_COM_DEFINITION_TASKml,
                        lastEquComDefinitionTask, plan_work_order);
                    PlanWorkOrder(ref plan_work_order, EQU_COM_DEFINITION_TASKml);
                    return webResponse.OK(ResponseType.Success);
                });
                //判断事务是否执行成功
                if (!webResponse1.Status)
                {
                    return new WebResponseContent().Error("返回消息");

                }

                //MQ_Send
                SendTaskToMQ(equmlcnc, EQU_COM_DEFINITION_TASKml);

                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                {
                    throw new Exception(ex.Message + ex.StackTrace);
                }

                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {

                Logger.Info(LoggerType.Login, eQU_COM_DEFINITION_TASK.Serialize(), webResponse.Message, msg);
            }

        }
        public async Task<WebResponseContent> PlcAlignRecordTask(PlcAlignRecordTask equ_TASKVM)
        {
            return await this.FnPlcAlignRecordTask(equ_TASKVM);
        }
        public async Task<WebResponseContent> Plcequ(Plcequ equ_TASKVM)
        {
            return await this.FnPlcequ(equ_TASKVM);
        }
        /// <summary>
        /// 返回任务 完成，重做，异常
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<WebResponseContent> Equ_ReturnTask(Equ_TaskReceive equ_TASKVM, IMapper _mapper)
        {
            return await this.ExecuteTask(equ_TASKVM, _mapper);
        }
        public async Task<WebResponseContent> Equ_ReturnTaskOrder(Equ_OrderReceive equ_TASKVM)
        {
            string msg = string.Empty;
            try
            {
                List<EQU_COM_DEFINITION_TASK> eQU_COM_DEFINITION_TASKs = await repository.FindAsync<EQU_COM_DEFINITION_TASK>(t => t.OrderCode == equ_TASKVM.OrderCode && t.Status == "3");

                foreach (var eQU_COM_DEFINITION_TASK in eQU_COM_DEFINITION_TASKs)
                {
                    // var id = equ_TASKVM.TaskNo;
                    EQU_EQUIPMENT equmlAction = null;
                    PLAN_WORK_ORDER plan_work_order = null;
                    PROC_PROGRAM procProgram = null;
                    if (equ_TASKVM.Status == "5")//任务重做
                    {
                        //  eQU_COM_DEFINITION_TASK = await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(t => t.TaskNo == id);
                        Guid equipment_Id = eQU_COM_DEFINITION_TASK.ActionEquipmentId != null ? Guid.Parse(eQU_COM_DEFINITION_TASK.ActionEquipmentId.ToString()) : Guid.NewGuid();
                        equmlAction = await repository.FindAsyncFirst<EQU_EQUIPMENT>(t => t.Id == equipment_Id);
                        if (equmlAction != null)
                        {
                            equmlAction.StateCode = 1;
                        }

                        eQU_COM_DEFINITION_TASK.Status = equ_TASKVM.Status;
                        eQU_COM_DEFINITION_TASK.ExecuteEnd = null;
                        eQU_COM_DEFINITION_TASK.ActionEquipmentId = null;
                        eQU_COM_DEFINITION_TASK.ExecuteStart = null;

                    }
                    else
                    {
                        //eQU_COM_DEFINITION_TASK = await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(t => t.TaskNo == id && t.ActionEquipmentId != null && t.Status == "2");
                        eQU_COM_DEFINITION_TASK.Status = equ_TASKVM.Status;
                        eQU_COM_DEFINITION_TASK.ExecuteEnd = DateTime.Now;
                        Guid equipment_Id = eQU_COM_DEFINITION_TASK.ActionEquipmentId != null ? Guid.Parse(eQU_COM_DEFINITION_TASK.ActionEquipmentId.ToString()) : Guid.NewGuid();
                        equmlAction = await repository.FindAsyncFirst<EQU_EQUIPMENT>(t => t.Id == equipment_Id);
                        if (equmlAction != null)
                        {
                            equmlAction.StateCode = 1;
                        }

                        if (!string.IsNullOrEmpty(eQU_COM_DEFINITION_TASK.ProgramId))
                        {
                            procProgram = await repository.FindAsyncFirst<PROC_PROGRAM>(t =>
                                t.Identifier == eQU_COM_DEFINITION_TASK.OrderCode &&
                                t.Id == Guid.Parse(eQU_COM_DEFINITION_TASK.ProgramId));
                            if (eQU_COM_DEFINITION_TASK.OperationName == "30141")
                            {
                                procProgram.UseState = "使用中";
                            }
                            if (eQU_COM_DEFINITION_TASK.OperationName == "30142" && equ_TASKVM.Status == "3")
                            {
                                procProgram.UseState = "已使用";
                            }
                        }

                        //   //执行完成 任务完成 TD100 TD200 TD300 TD400
                        if (equ_TASKVM.Status == "3" && eQU_COM_DEFINITION_TASK.Command == "TD100")//紧急暂停stop
                        {
                            plan_work_order = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode);
                            plan_work_order.process_Status = (int)StatusProcess.EmergencyPause;// ((int)StatusOrder.New).ToString();//0新建 
                        }
                        else if (equ_TASKVM.Status == "3" && eQU_COM_DEFINITION_TASK.Command == "TD200")//	暂停pause
                        {
                            plan_work_order = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode);
                            plan_work_order.process_Status = (int)StatusProcess.Pause;
                        }
                        else if (equ_TASKVM.Status == "3" && eQU_COM_DEFINITION_TASK.Command == "TD300")//启动start
                        {
                            plan_work_order = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode);
                            plan_work_order.process_Status = (int)StatusProcess.Produce;
                        }
                        else if (equ_TASKVM.Status == "3" && eQU_COM_DEFINITION_TASK.Command == "TD400")//	终止termination
                        {
                            plan_work_order = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode);
                            plan_work_order.process_Status = (int)StatusProcess.Stop;
                        }
                    }
                    if (eQU_COM_DEFINITION_TASK == null)
                    {
                        Logger.Info(LoggerType.Login, "此次执行任务没有设备", webResponse.Message, msg);
                        return webResponse.Error("此次执行任务没有设备");
                    }
                    using (var transaction = repository.DbContext.Database.BeginTransaction())
                    {
                        repository.Update<EQU_COM_DEFINITION_TASK>(eQU_COM_DEFINITION_TASK, true);
                        if (equmlAction != null)
                        {
                            repository.Update<EQU_EQUIPMENT>(equmlAction, true);
                        }

                        if (plan_work_order != null)
                        {
                            repository.Update<PLAN_WORK_ORDER>(plan_work_order, true);
                        }

                        if (procProgram != null)
                        {
                            repository.Update<PROC_PROGRAM>(procProgram, true);
                        }
                        transaction.Commit();
                    }
                }


                Logger.Info(LoggerType.Success, equ_TASKVM.Serialize(), webResponse.Message, msg);
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                {
                    throw new Exception(ex.Message + ex.StackTrace);
                }
                Logger.Info(LoggerType.Exception, equ_TASKVM.Serialize(), webResponse.Message, msg);
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {
                Logger.Info(LoggerType.Login, equ_TASKVM.Serialize(), webResponse.Message, msg);
            }
        }
        /// <summary>
        /// 再次执行
        /// </summary>
        /// <param name="taskgenerate"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> TaskExecuteAgain(Equ_TaskReceive equ_TASKVM, IMapper _mapper)
        {
            return await ExecuteTask(equ_TASKVM, _mapper);


        }
        async Task<WebResponseContent> FnPlcequ(Plcequ plcequ)
        {
            string msg = string.Empty;
            EQU_EQUIPMENT eQU_EQUIPMENT = null;

            try
            {

                eQU_EQUIPMENT = await repository.FindAsyncFirst<EQU_EQUIPMENT>(t => t.EquipmentNo == plcequ.CNC_NUM);

                if (eQU_EQUIPMENT != null)
                {
                    //Logger.Info(LoggerType.Login, "此次执行任务没有设备", webResponse.Message, msg);
                    //return webResponse.Error("此次执行任务没有设备");
                    eQU_EQUIPMENT.OpenedDoor1 = plcequ.OpenedDoor1;
                    eQU_EQUIPMENT.ClosedDoor1 = plcequ.ClosedDoor1;
                    eQU_EQUIPMENT.OpenedDoor2 = plcequ.OpenedDoor2;
                    eQU_EQUIPMENT.ClosedDoor2 = plcequ.ClosedDoor2;
                    eQU_EQUIPMENT.OpenedDuiDaoDoor = plcequ.OpenedDuiDaoDoor;
                    eQU_EQUIPMENT.ClosedDuiDaoDoor = plcequ.ClosedDuiDaoDoor;
                    eQU_EQUIPMENT.OpenedDangliao = plcequ.OpenedDangliao;
                    eQU_EQUIPMENT.ClosedDangliao = plcequ.ClosedDangliao;
                    eQU_EQUIPMENT.OpenedCi = plcequ.OpenedCi;
                    eQU_EQUIPMENT.ClosedCi = plcequ.ClosedCi;
                    eQU_EQUIPMENT.WarningCi = plcequ.WarningCi;
                    eQU_EQUIPMENT.JiaDao = plcequ.JiaDao;
                    eQU_EQUIPMENT.SongDao = plcequ.SongDao;
                    eQU_EQUIPMENT.M30 = plcequ.M30;
                    eQU_EQUIPMENT.AllowShangXiaHuan = plcequ.AllowShangXiaHuan;
                    eQU_EQUIPMENT.AllowHuanDao = plcequ.AllowHuanDao;
                    eQU_EQUIPMENT.RunStatus = plcequ.RunStatus;
                    eQU_EQUIPMENT.RunTime = DateTime.Parse(plcequ.Time);

                }
                else
                {
                    Logger.Info(LoggerType.Login, "没有设备", webResponse.Message, msg);
                    return webResponse.Error("没有设备");
                }

                WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
                {

                    if (eQU_EQUIPMENT != null)
                    {
                        repository.DbContext.Set<EQU_EQUIPMENT>().Update(eQU_EQUIPMENT);
                        repository.DbContext.SaveChanges();

                    }
                    return webResponse.OK(ResponseType.Success);
                });

                Logger.Info(LoggerType.Success, eQU_EQUIPMENT.Serialize(), webResponse.Message, msg);
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                {
                    throw new Exception(ex.Message + ex.StackTrace);
                }
                Logger.Info(LoggerType.Exception, eQU_EQUIPMENT.Serialize(), webResponse.Message, msg);
                return webResponse.Error(ResponseType.ServerError);
            }

        }
        /// <summary>
        /// PLC推棒数据
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        async Task<WebResponseContent> FnPlcAlignRecordTask(PlcAlignRecordTask equ_TASKVM)
        {
            string msg = string.Empty;
            try
            {
                EQU_COM_DEFINITION_TASK eQU_COM_DEFINITION_TASK = null;
                var id = equ_TASKVM.TaskNo;
                EQU_COM_DEFINITION_TASK_RECORD eQU_COM_DEFINITION_TASK_RECORD = null;
                EQU_FAULT_PHENOMENON eQU_FAULT_PHENOMENON = null;

                eQU_COM_DEFINITION_TASK = await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(t => t.TaskNo == id);


                if (eQU_COM_DEFINITION_TASK == null)
                {
                    //Logger.Info(LoggerType.Login, "此次执行任务没有设备", webResponse.Message, msg);
                    //return webResponse.Error("此次执行任务没有设备");
                    eQU_COM_DEFINITION_TASK_RECORD = new EQU_COM_DEFINITION_TASK_RECORD();

                    eQU_COM_DEFINITION_TASK_RECORD.AY = equ_TASKVM.AY;
                    eQU_COM_DEFINITION_TASK_RECORD.BY = equ_TASKVM.BY;
                    eQU_COM_DEFINITION_TASK_RECORD.ABInstance = equ_TASKVM.ABInstance;
                    eQU_COM_DEFINITION_TASK_RECORD.ARealityY = equ_TASKVM.ARealityY;
                    eQU_COM_DEFINITION_TASK_RECORD.BRealityY = equ_TASKVM.BRealityY;
                    eQU_COM_DEFINITION_TASK_RECORD.StepLocation = equ_TASKVM.StepLocation;
                    eQU_COM_DEFINITION_TASK_RECORD.FirstStopLocation = equ_TASKVM.FirstStopLocation;
                    eQU_COM_DEFINITION_TASK_RECORD.AllinValue = equ_TASKVM.AllinValue;
                    eQU_COM_DEFINITION_TASK_RECORD.TwoDistance = equ_TASKVM.TwoDistance;
                    eQU_COM_DEFINITION_TASK_RECORD.NeedValue = equ_TASKVM.NeedValue;
                    eQU_COM_DEFINITION_TASK_RECORD.NeedDistance = equ_TASKVM.NeedDistance;
                    eQU_COM_DEFINITION_TASK_RECORD.BitVariable00 = equ_TASKVM.BitVariable00;

                    eQU_COM_DEFINITION_TASK_RECORD.CreateOn = DateTime.Now;

                }
                else
                {
                    var pLAN_WORK = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode);
                    eQU_COM_DEFINITION_TASK_RECORD = new EQU_COM_DEFINITION_TASK_RECORD();
                    eQU_COM_DEFINITION_TASK_RECORD.EQUTask_Id = eQU_COM_DEFINITION_TASK.EQUTask_Id;
                    eQU_COM_DEFINITION_TASK_RECORD.Equipment_Id = eQU_COM_DEFINITION_TASK.Equipment_Id;
                    eQU_COM_DEFINITION_TASK_RECORD.OrderCode = eQU_COM_DEFINITION_TASK.OrderCode;
                    eQU_COM_DEFINITION_TASK_RECORD.AY = equ_TASKVM.AY;
                    eQU_COM_DEFINITION_TASK_RECORD.BY = equ_TASKVM.BY;
                    eQU_COM_DEFINITION_TASK_RECORD.ABInstance = equ_TASKVM.ABInstance;
                    eQU_COM_DEFINITION_TASK_RECORD.ARealityY = equ_TASKVM.ARealityY;
                    eQU_COM_DEFINITION_TASK_RECORD.BRealityY = equ_TASKVM.BRealityY;
                    eQU_COM_DEFINITION_TASK_RECORD.StepLocation = equ_TASKVM.StepLocation;
                    eQU_COM_DEFINITION_TASK_RECORD.FirstStopLocation = equ_TASKVM.FirstStopLocation;
                    eQU_COM_DEFINITION_TASK_RECORD.AllinValue = equ_TASKVM.AllinValue;
                    eQU_COM_DEFINITION_TASK_RECORD.TwoDistance = equ_TASKVM.TwoDistance;
                    eQU_COM_DEFINITION_TASK_RECORD.NeedValue = equ_TASKVM.NeedValue;
                    eQU_COM_DEFINITION_TASK_RECORD.NeedDistance = equ_TASKVM.NeedDistance;
                    eQU_COM_DEFINITION_TASK_RECORD.BitVariable00 = equ_TASKVM.BitVariable00;
                    eQU_COM_DEFINITION_TASK_RECORD.OperationName = eQU_COM_DEFINITION_TASK.OperationName;
                    eQU_COM_DEFINITION_TASK_RECORD.Command = eQU_COM_DEFINITION_TASK.Command;
                    eQU_COM_DEFINITION_TASK_RECORD.CreateOn = DateTime.Now;
                    eQU_COM_DEFINITION_TASK_RECORD.ComDefintion_TaskId = eQU_COM_DEFINITION_TASK.ComDefintion_TaskId.ToString().ToUpper();
                    eQU_COM_DEFINITION_TASK_RECORD.Description = pLAN_WORK.ProcessWeight.ToString();
                }



                WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
                        {

                            if (eQU_COM_DEFINITION_TASK_RECORD != null)
                            {
                                //await repository.DbContext.AddAsync<EQU_TOOL>(mladd); 
                                repository.DbContext.Set<EQU_COM_DEFINITION_TASK_RECORD>().Add(eQU_COM_DEFINITION_TASK_RECORD);
                                repository.DbContext.SaveChanges();
                                //   repository.AddRange<EQU_FAULT_PHENOMENON>(eQU_FAULT_PHENOMENON, true);
                            }
                            return webResponse.OK(ResponseType.Success);
                        });

                Logger.Info(LoggerType.Success, equ_TASKVM.Serialize(), webResponse.Message, msg);
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                {
                    throw new Exception(ex.Message + ex.StackTrace);
                }
                Logger.Info(LoggerType.Exception, equ_TASKVM.Serialize(), webResponse.Message, msg);
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {
                Logger.Info(LoggerType.Login, equ_TASKVM.Serialize(), webResponse.Message, msg);
            }
        }
        /// <summary>
        /// 返回任务 完成，重做，异常
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        async Task<WebResponseContent> ExecuteTask(Equ_TaskReceive equ_TASKVM, IMapper _mapper)
        {
            string msg = string.Empty;
            var dt = DateTime.Now;
            try
            {
                EQU_COM_DEFINITION_TASK eQU_COM_DEFINITION_TASK = null;
                var id = equ_TASKVM.TaskNo;
                EQU_EQUIPMENT equmlAction = null;
                PLAN_WORK_ORDER plan_work_order = null;
                EQU_FAULT_PHENOMENON eQU_FAULT_PHENOMENON = null;
                EQU_FAULT_PHENOMENON eQU_FAULT_PHENOMENON_TZ = null;
                EQU_FAULT_PHENOMENON eQU_FAULT_PHENOMENON_Finish= null;
                PROC_PROGRAM procProgram = null;
                EQU_TOOL eQU_TOOL = null;
                eQU_COM_DEFINITION_TASK = await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(t => t.TaskNo == id);
                if (eQU_COM_DEFINITION_TASK == null)
                {
                    Logger.Info(LoggerType.Login, "无此次执行任务【" + id + "】", webResponse.Message, msg);
                    return webResponse.Error("无此次执行任务【" + id + "】");
                }
                //if (eQU_COM_DEFINITION_TASK.Status == "2")
                //{
                //    Logger.Info(LoggerType.Login, "此次执行任务【" + id + "】正在执行", webResponse.Message, msg);
                //    return webResponse.Error("此次执行任务【" + id + "】正在执行");
                //}
                var currentequmlAction = await repository.FindAsyncFirst<EQU_EQUIPMENT>(t => t.Id == Guid.Parse(eQU_COM_DEFINITION_TASK.Equipment_Id.ToString().ToUpper()));
                plan_work_order = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode);
                if (eQU_COM_DEFINITION_TASK.Command == "TW004" || eQU_COM_DEFINITION_TASK.Command == "TW0041")
                {
                    procProgram = await repository.FindAsyncFirst<PROC_PROGRAM>(t => t.Identifier == eQU_COM_DEFINITION_TASK.OrderCode && t.Id == Guid.Parse(eQU_COM_DEFINITION_TASK.ProgramId));
                    eQU_TOOL = await repository.FindAsyncFirst<EQU_TOOL>(t => t.Identifier == eQU_COM_DEFINITION_TASK.OrderCode && t.program_seq == procProgram.sequence);
                   var eQU_TOOLCount =  repository.Find<EQU_TOOL>(t => t.Identifier == eQU_COM_DEFINITION_TASK.OrderCode && t.program_seq > procProgram.sequence&&t.reality_pairing_length>0).Count();
                    //换刀通知
                    if (eQU_COM_DEFINITION_TASK.Command == "TW004")
                     {
                        eQU_FAULT_PHENOMENON_TZ = new EQU_FAULT_PHENOMENON();
                        eQU_FAULT_PHENOMENON_TZ.TaskNo = id;
                        eQU_FAULT_PHENOMENON_TZ.Content =$"【{currentequmlAction.EquipmentNameZH}】【{currentequmlAction.EquipmentNo}】开始第【{eQU_TOOL.program_seq.ToString()}】程序";
                        eQU_FAULT_PHENOMENON_TZ.FunctionType = "换刀通知";
                        eQU_FAULT_PHENOMENON_TZ.OrderId =  plan_work_order.Order_Id.ToString().ToUpper();
                        eQU_FAULT_PHENOMENON_TZ.CreateOn = DateTime.Now;
                        eQU_FAULT_PHENOMENON_TZ.FunctionType = "换刀通知";
                    }
                    if (eQU_COM_DEFINITION_TASK.Command == "TW0041" && equ_TASKVM.Status=="3" && eQU_TOOLCount==0)
                    {
                        eQU_FAULT_PHENOMENON_TZ = new EQU_FAULT_PHENOMENON();
                        eQU_FAULT_PHENOMENON_TZ.TaskNo = id;
                        eQU_FAULT_PHENOMENON_TZ.Content = $"【{currentequmlAction.EquipmentNameZH}】【{currentequmlAction.EquipmentNo}】结束第【{eQU_TOOL.program_seq.ToString()}】程序，刀库已无刀";
                        eQU_FAULT_PHENOMENON_TZ.FunctionType = "换刀通知";
                        eQU_FAULT_PHENOMENON_TZ.OrderId = plan_work_order.Order_Id.ToString().ToUpper();
                        eQU_FAULT_PHENOMENON_TZ.CreateOn = DateTime.Now;
                        eQU_FAULT_PHENOMENON_TZ.FunctionType = "换刀通知";
                    }

                }
                
                
                if (currentequmlAction != null && eQU_COM_DEFINITION_TASK.Command != "TW006")
                {

                    currentequmlAction.CurrentOrder = eQU_COM_DEFINITION_TASK.OrderCode;
                    plan_work_order.Status = ((int)StatusOrder.Produce).ToString();
                    plan_work_order.process_Status = (int)StatusProcess.Produce;

                }
                if (equ_TASKVM.Status == "5")//任务重做
                {

                    currentequmlAction = null;
                    Guid equipment_Id = eQU_COM_DEFINITION_TASK.ActionEquipmentId != null ? Guid.Parse(eQU_COM_DEFINITION_TASK.ActionEquipmentId.ToString()) : Guid.NewGuid();
                    equmlAction = await repository.FindAsyncFirst<EQU_EQUIPMENT>(t => t.Id == equipment_Id);
                    if (equmlAction != null)
                    {
                        equmlAction.StateCode = 1;

                    }

                    eQU_COM_DEFINITION_TASK.Status = equ_TASKVM.Status;
                    eQU_COM_DEFINITION_TASK.ExecuteEnd = null;
                    eQU_COM_DEFINITION_TASK.ActionEquipmentId = null;
                    eQU_COM_DEFINITION_TASK.ExecuteStart = null;


                }
                else if (equ_TASKVM.Status == "4")
                {
                    //异常
                    if (equ_TASKVM.Status == "4" && !string.IsNullOrEmpty(equ_TASKVM.FaultContent))
                    {
                        eQU_COM_DEFINITION_TASK.Description = equ_TASKVM.FaultContent;
                        eQU_COM_DEFINITION_TASK.Status = equ_TASKVM.Status;
                        eQU_COM_DEFINITION_TASK.LastUpdateOn = DateTime.Now;
                        eQU_FAULT_PHENOMENON = new EQU_FAULT_PHENOMENON();
                        eQU_FAULT_PHENOMENON.TaskNo = id;
                        eQU_FAULT_PHENOMENON.Content = equ_TASKVM.FaultContent;
                        eQU_FAULT_PHENOMENON.FunctionType = equ_TASKVM.FaultType;
                        eQU_FAULT_PHENOMENON.OrderId = plan_work_order.Order_Id.ToString().ToUpper();
                        eQU_FAULT_PHENOMENON.CreateOn = DateTime.Now;
                    }
                }
                else if (string.IsNullOrEmpty(equ_TASKVM.Status) && !string.IsNullOrEmpty(equ_TASKVM.FaultContent))
                {
                    //            
                    eQU_COM_DEFINITION_TASK.LastUpdateOn = DateTime.Now;
                    eQU_FAULT_PHENOMENON = new EQU_FAULT_PHENOMENON();
                    eQU_FAULT_PHENOMENON.TaskNo = id;
                    eQU_FAULT_PHENOMENON.Content = equ_TASKVM.FaultContent;
                    eQU_FAULT_PHENOMENON.FunctionType = equ_TASKVM.FaultType;
                    eQU_FAULT_PHENOMENON.OrderId = plan_work_order.Order_Id.ToString().ToUpper();
                    eQU_FAULT_PHENOMENON.CreateOn = DateTime.Now;

                }
                else
                {

                    if (eQU_TOOL != null && eQU_COM_DEFINITION_TASK.Command == "TW0041")
                    {
                        eQU_TOOL.process_end_time = dt;

                        if(plan_work_order.UsedToolTotal== eQU_TOOL.program_seq)
                        {
                            //所有程序已加工完
                            eQU_FAULT_PHENOMENON_Finish = new EQU_FAULT_PHENOMENON();
                            eQU_FAULT_PHENOMENON_Finish.TaskNo = id;
                            eQU_FAULT_PHENOMENON_Finish.Content = $"【{currentequmlAction.EquipmentNameZH}】【{currentequmlAction.EquipmentNo}】已完最后第【{eQU_TOOL.program_seq.ToString()}】程序";
                            eQU_FAULT_PHENOMENON_Finish.FunctionType = "其他";
                            eQU_FAULT_PHENOMENON_Finish.OrderId = plan_work_order.Order_Id.ToString().ToUpper();
                            eQU_FAULT_PHENOMENON_Finish.CreateOn = DateTime.Now;
                            if (equ_TASKVM.Status == "3" && currentequmlAction.EquipmentNameZH == "新代")
                            {
                                plan_work_order.Status = ((int)StatusOrder.Completed).ToString();
                                plan_work_order.process_Status = (int)StatusProcess.Completed;
                                currentequmlAction.CurrentOrder = "";
                                plan_work_order.IsActivation = "0";//停用下发
                            }
                        }
                        
                    }
                    eQU_COM_DEFINITION_TASK = await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(t => t.TaskNo == id && t.ActionEquipmentId != null && (t.Status == "2"));
                    if (eQU_COM_DEFINITION_TASK != null)
                    {
                        eQU_COM_DEFINITION_TASK.Status = equ_TASKVM.Status;
                        eQU_COM_DEFINITION_TASK.ExecuteEnd = dt;
                    }
                    else
                    {
                        Logger.Info(LoggerType.Login, "此次执行任务【" + id + "】没有设备", webResponse.Message, msg);
                        return webResponse.Error("此次执行任务【" + id + "】没有设备");
                    }
                    Guid equipment_Id = eQU_COM_DEFINITION_TASK.ActionEquipmentId != null ? Guid.Parse(eQU_COM_DEFINITION_TASK.ActionEquipmentId.ToString()) : Guid.NewGuid();
                    equmlAction = await repository.FindAsyncFirst<EQU_EQUIPMENT>(t => t.Id == equipment_Id);
                    if (equmlAction != null)
                    {
                        equmlAction.StateCode = 1;

                    }
                    //   //执行完成 任务完成 TD100 TD200 TD300 TD400
                    if (equ_TASKVM.Status == "3" && eQU_COM_DEFINITION_TASK.Command == "TD100")//紧急暂停stop
                    {
                        plan_work_order = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode);
                        plan_work_order.process_Status = (int)StatusProcess.EmergencyPause;// ((int)StatusOrder.New).ToString();//0新建 
                    }
                    else if (equ_TASKVM.Status == "3" && eQU_COM_DEFINITION_TASK.Command == "TD200")//	暂停pause
                    {
                        plan_work_order = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode);
                        plan_work_order.process_Status = (int)StatusProcess.Pause;
                    }
                    else if (equ_TASKVM.Status == "3" && eQU_COM_DEFINITION_TASK.Command == "TD300")//启动start
                    {
                        plan_work_order = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode);
                        plan_work_order.process_Status = (int)StatusProcess.Produce;
                    }
                    else if (equ_TASKVM.Status == "3" && eQU_COM_DEFINITION_TASK.Command == "TD400")//	终止termination
                    {
                        plan_work_order = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode);
                        plan_work_order.process_Status = (int)StatusProcess.Stop;

                    }
                    else if (equ_TASKVM.Status == "3" && eQU_COM_DEFINITION_TASK.Command == "TW001")//工件入库完成自动启动下发
                    {
                        plan_work_order = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode);
                        if (plan_work_order.IsActivation != "1")
                        {
                            plan_work_order.IsActivation = "1";//启用下发
                            repository.Update<PLAN_WORK_ORDER>(plan_work_order, true);
                        }
                    }
                    else if (equ_TASKVM.Status == "3" && eQU_COM_DEFINITION_TASK.Command == "TW003")//工件上料完成自动清空库存
                    {

                        var procMaterial = repository.DbContext.Set<PROC_MATERIAL>().Where(t => t.Order_Id == plan_work_order.Order_Id.ToString().ToUpper()).FirstOrDefault();
                        var pROC_CALL_MATERIAL = repository.DbContext.Set<PROC_CALL_MATERIAL>().Where(t => t.Order_Id == plan_work_order.Order_Id.ToString().ToUpper()).FirstOrDefault();
                        if (procMaterial != null)
                        {
                            procMaterial.PlanStart = plan_work_order.PlanStart;
                            procMaterial.PlanEnd = plan_work_order.PlanEnd;
                            procMaterial.StorageState = "未入库";
                            procMaterial.SHELVES_Id = null;
                            repository.DbContext.Set<PROC_MATERIAL>().Update(procMaterial);
                        }
                        if (pROC_CALL_MATERIAL != null)
                        {
                            pROC_CALL_MATERIAL.PlanStart = plan_work_order.PlanStart;
                            pROC_CALL_MATERIAL.PlanEnd = plan_work_order.PlanEnd;
                            pROC_CALL_MATERIAL.StorageState = "未入库";
                            pROC_CALL_MATERIAL.SHELVES_Id = null;
                            repository.DbContext.Set<PROC_CALL_MATERIAL>().Update(pROC_CALL_MATERIAL);
                        }
                        if (plan_work_order.IsActivation != "1")
                        {
                            plan_work_order.IsActivation = "1";//启用下发
                            repository.Update<PLAN_WORK_ORDER>(plan_work_order, true);
                        }
                    }
                    else if (equ_TASKVM.Status == "3" && eQU_COM_DEFINITION_TASK.Command == "TW004")
                    {
                        var usedToolCount = await repository.DbContext.Set<EQU_COM_DEFINITION_TASK>().Where(t => t.Command == "TW004" && t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode && t.ExecuteTaskDiffTime > 0).CountAsync();
                        plan_work_order.UsedToolCount = usedToolCount;
                        if (plan_work_order.OrderQuantity >= plan_work_order.ProcessingNumber)
                        {
                            eQU_COM_DEFINITION_TASK.ProcessingNumber = eQU_COM_DEFINITION_TASK.ProcessingNumber != null ? eQU_COM_DEFINITION_TASK.ProcessingNumber : 0 + 1;
                            plan_work_order.ProcessingNumber = eQU_COM_DEFINITION_TASK.ProcessingNumber;
                        }


                    }
                    else if (equ_TASKVM.Status == "3" && eQU_COM_DEFINITION_TASK.Command == "TW0041")//
                    {
                        var usedToolCount = await repository.DbContext.Set<EQU_COM_DEFINITION_TASK>().Where(t => t.Command == "TW0041" && t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode&&t.Status=="3").CountAsync();
                        plan_work_order.UsedToolCount = usedToolCount+1;
                        if (plan_work_order.OrderQuantity >= plan_work_order.ProcessingNumber)
                        {
                            eQU_COM_DEFINITION_TASK.ProcessingNumber = eQU_COM_DEFINITION_TASK.ProcessingNumber != null ? eQU_COM_DEFINITION_TASK.ProcessingNumber : 0 + 1;
                            plan_work_order.ProcessingNumber = eQU_COM_DEFINITION_TASK.ProcessingNumber;
                        }
                        


                    }
                    else if (equ_TASKVM.Status == "3" && eQU_COM_DEFINITION_TASK.Command == "TW006")
                    {
                        plan_work_order.Status = ((int)StatusOrder.Completed).ToString();
                        plan_work_order.process_Status = (int)StatusProcess.Completed;
                        currentequmlAction.CurrentOrder = "";
                        plan_work_order.IsActivation = "0";//停用下发
                    }
                }



                WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
                {
                    if (eQU_TOOL != null)
                    {

                        repository.Update<EQU_TOOL>(eQU_TOOL, true);
                    }
                    if (procProgram != null)
                    { eQU_COM_DEFINITION_TASK.ProcessingNumber = procProgram.sequence; }

                    repository.Update<EQU_COM_DEFINITION_TASK>(eQU_COM_DEFINITION_TASK, true);
                    if (equmlAction != null)
                    {

                        repository.Update<EQU_EQUIPMENT>(equmlAction, true);
                        repository.DbContext.SaveChanges();
                    }
                    if (currentequmlAction != null)
                    {
                        repository.Update<EQU_EQUIPMENT>(currentequmlAction, true);
                        repository.DbContext.SaveChanges();
                    }
                    if (plan_work_order != null)
                    {
                        repository.Update<PLAN_WORK_ORDER>(plan_work_order, true);
                        repository.DbContext.SaveChanges();
                    }
                    if (eQU_FAULT_PHENOMENON != null)
                    {
                        //await repository.DbContext.AddAsync<EQU_TOOL>(mladd); 
                        eQU_FAULT_PHENOMENON.FunctionType = "生产异常";
                        repository.DbContext.Set<EQU_FAULT_PHENOMENON>().Add(eQU_FAULT_PHENOMENON);
                        repository.DbContext.SaveChanges();
                    }
                    if(eQU_FAULT_PHENOMENON_TZ!=null)
                    {
                        repository.DbContext.Set<EQU_FAULT_PHENOMENON>().Add(eQU_FAULT_PHENOMENON_TZ);
                        repository.DbContext.SaveChanges();
                    }
                    if(eQU_FAULT_PHENOMENON_Finish!=null)
                    {
                        repository.DbContext.Set<EQU_FAULT_PHENOMENON>().Add(eQU_FAULT_PHENOMENON_Finish);
                        repository.DbContext.SaveChanges();
                    }
                    return webResponse.OK(ResponseType.Success);
                });
                if (eQU_COM_DEFINITION_TASK.Command == "TW004" || eQU_COM_DEFINITION_TASK.Command == "TW0041")
                {
                    var order = plan_work_order.OrderCode;
                    var sumTime = repository.Find<EQU_COM_DEFINITION_TASK>(t => t.OrderCode == order && t.ExecuteTaskDiffTime != null && (t.Command == "TW004" || t.Command == "TW0041")).Sum(t => t.ExecuteTaskDiffTime);
                    plan_work_order.ProcessingTime = sumTime;
                    if (procProgram != null)
                    {
                        plan_work_order.ProcessingNumber = procProgram.sequence;
                    }

                    if (plan_work_order != null)
                    {
                        repository.DbContext.Set<PLAN_WORK_ORDER>().Update(plan_work_order);
                    }
                }
                var EQU_COM_DEFINITION_TASKLog = repository.Find<EQU_COM_DEFINITION_TASK>(t => t.TaskNo == eQU_COM_DEFINITION_TASK.TaskNo)
                  .FirstOrDefault();
                if (EQU_COM_DEFINITION_TASKLog != null)
                {
                    var tASK_LOGs = _mapper.Map<EQU_COM_DEFINITION_TASK_LOG>(EQU_COM_DEFINITION_TASKLog);
                    //   EQU_COM_DEFINITION_TASKLog.Status = "2";
                    repository.DbContext.Set<EQU_COM_DEFINITION_TASK_LOG>().AddRange(tASK_LOGs);
                }
                repository.DbContext.SaveChanges();
                Logger.Info(LoggerType.Success, equ_TASKVM.Serialize(), webResponse.Message, msg);
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                //if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                //{
                //    throw new Exception(ex.Message + ex.StackTrace);
                //}
                Logger.Info(LoggerType.Exception, equ_TASKVM.Serialize(), webResponse.Message, msg);
                return webResponse.Error(msg);
            }
            finally
            {
                Logger.Info(LoggerType.Login, equ_TASKVM.Serialize(), webResponse.Message, msg);
            }
        }
        public async Task<WebResponseContent> Taskgenerate(Taskgenerate taskgenerate)
        {
            string msg = string.Empty;
            try
            {
                EQU_COM_DEFINITION_TASK eQU_COM_DEFINITION_TASK = null;
                List<EQU_COM_DEFINITION_TASK> eQU_COM_DEFINITION_TASKList = new List<EQU_COM_DEFINITION_TASK>();
                List<EQU_COM_DEFINITION_TASK> taskList = new List<EQU_COM_DEFINITION_TASK>();
                List<PROC_PROGRAM> pROC_PROGRAMs = null;
                List<PROC_PROGRAM> pROC_PROGRAMsNew = null;
                List<EQU_TOOL_PROGAME> pROC_TOOL_PROGAMEs = new List<EQU_TOOL_PROGAME>();
                List<EQU_TOOL> tools = new List<EQU_TOOL>();
                EQU_EQUIPMENT equmlAction = null;
                PLAN_WORK_ORDER plan_work_order = null;
                if (!string.IsNullOrEmpty(taskgenerate.OrderCode))//
                {
                    pROC_TOOL_PROGAMEs = await repository.FindAsync<EQU_TOOL_PROGAME>(t => t.OrderCode == taskgenerate.OrderCode && t.ExecuteSort > 1 && t.Status != "1");
                    plan_work_order = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.OrderCode == taskgenerate.OrderCode);
                    var ver = int.Parse(plan_work_order.Version) + 1;
                    plan_work_order.Version = ver.ToString();
                    pROC_PROGRAMs = await repository.FindAsync<PROC_PROGRAM>(t => t.Identifier == taskgenerate.OrderCode);
                    eQU_COM_DEFINITION_TASKList = await repository.FindAsync<EQU_COM_DEFINITION_TASK>(t => t.OrderCode == taskgenerate.OrderCode && t.ProgramId != "");

                    var arrytask = eQU_COM_DEFINITION_TASKList.Select(t1 => t1.ProgramId).ToList();
                    var arrypro = pROC_PROGRAMs.Select(t1 => t1.Id.ToString().ToUpper()).ToList();
                    var arry = arrypro.Except(arrytask).ToArray();
                    pROC_PROGRAMsNew = pROC_PROGRAMs.Where(t => arry.Contains(t.Id.ToString().ToUpper())).ToList();

                    var arry1 = pROC_PROGRAMsNew.Select(t => t.sequence).ToArray();
                    var arry2 = pROC_PROGRAMs.Where(t => arry1.Contains(t.sequence)).Select(t1 => t1.Id.ToString().ToUpper()).ToArray();
                    taskList = await repository.FindAsync<EQU_COM_DEFINITION_TASK>(t => t.OrderCode == taskgenerate.OrderCode && arry2.Contains(t.ProgramId));
                    tools = await repository.FindAsync<EQU_TOOL>(t => t.Identifier == taskgenerate.OrderCode);
                }
                var taskTW004 = await repository.FindAsync<EQU_COM_DEFINITION_TASK>(t => t.OrderCode == taskgenerate.OrderCode && t.Command == "TW004" && t.ProgramId != "");
                var taskTW0041 = await repository.FindAsync<EQU_COM_DEFINITION_TASK>(t => t.OrderCode == taskgenerate.OrderCode && t.Command == "TW0041" && t.ProgramId != "");
                WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
                {
                    List<EQU_COM_DEFINITION_TASK> eQU_COM_DEFINITION_TASKListAdd = new List<EQU_COM_DEFINITION_TASK>();


                    //2.无新增加程序和刀具，利用已有刀和程序生成换刀和加工任务
                    foreach (var proc_tool_progame in pROC_TOOL_PROGAMEs)
                    {
                        var fristTaskTW004 = taskTW004.Where(t => t.ProgramId == proc_tool_progame.ProgrameId.ToString().ToUpper()).FirstOrDefault();
                        var fristtaskTW0041 = taskTW0041.Where(t => t.ProgramId == proc_tool_progame.ProgrameId.ToString().ToUpper()).FirstOrDefault();
                        if (fristTaskTW004 != null)
                        {
                            EQU_COM_DEFINITION_TASK eQU_COM_DEFINITION_TASKNew = new EQU_COM_DEFINITION_TASK();
                            eQU_COM_DEFINITION_TASKNew.ProgramId = proc_tool_progame.ProgrameId.ToString().ToUpper();
                            eQU_COM_DEFINITION_TASKNew.SecornSeq = fristTaskTW004.SecornSeq;
                            eQU_COM_DEFINITION_TASKNew.OrderCode = proc_tool_progame.OrderCode;
                            eQU_COM_DEFINITION_TASKNew.TaskNo = fristTaskTW004.TaskNo + "-" + proc_tool_progame.ExecuteSort;
                            eQU_COM_DEFINITION_TASKNew.Command = fristTaskTW004.Command;
                            eQU_COM_DEFINITION_TASKNew.Status = "1";
                            //var firstdes = taskList.OrderByDescending(t => t.ActionSort).FirstOrDefault();
                            eQU_COM_DEFINITION_TASKNew.ActionSort = (fristTaskTW004.ActionSort + 1) + ((proc_tool_progame.ExecuteSort.Value) * 0.1m) + ((1) * 0.01m);
                            eQU_COM_DEFINITION_TASKNew.ToolId = proc_tool_progame.ToolId.ToString().ToUpper();
                            eQU_COM_DEFINITION_TASKNew.OperationName = fristTaskTW004.OperationName;
                            eQU_COM_DEFINITION_TASKNew.Equipment_Id = fristTaskTW004.Equipment_Id;
                            eQU_COM_DEFINITION_TASKNew.EQUTask_Id = fristTaskTW004.EQUTask_Id;
                            eQU_COM_DEFINITION_TASKNew.SubPathNo = fristTaskTW004.SubPathNo;
                            eQU_COM_DEFINITION_TASKNew.CreateOn = DateTime.Now;
                            eQU_COM_DEFINITION_TASKNew.CreateBy = UserContext.Current.UserName;
                            //ActionSort, OperationName,EQUTask_Id,SubPathNo,Equipment_Id
                            eQU_COM_DEFINITION_TASKListAdd.Add(eQU_COM_DEFINITION_TASKNew);
                        }
                        if (fristtaskTW0041 != null)
                        {
                            EQU_COM_DEFINITION_TASK eQU_COM_DEFINITION_TASKNew = new EQU_COM_DEFINITION_TASK();
                            eQU_COM_DEFINITION_TASKNew.ProgramId = proc_tool_progame.ProgrameId.ToString().ToUpper();
                            eQU_COM_DEFINITION_TASKNew.SecornSeq = fristtaskTW0041.SecornSeq;
                            eQU_COM_DEFINITION_TASKNew.OrderCode = proc_tool_progame.OrderCode;
                            eQU_COM_DEFINITION_TASKNew.TaskNo = fristtaskTW0041.TaskNo + "-" + proc_tool_progame.ExecuteSort;
                            eQU_COM_DEFINITION_TASKNew.Command = fristtaskTW0041.Command;
                            eQU_COM_DEFINITION_TASKNew.Status = "1";
                            // var firstdes = taskList.OrderByDescending(t => t.ActionSort).FirstOrDefault();
                            eQU_COM_DEFINITION_TASKNew.ActionSort = fristtaskTW0041.ActionSort + ((proc_tool_progame.ExecuteSort.Value) * 0.1m) + ((2) * 0.01m);
                            eQU_COM_DEFINITION_TASKNew.ToolId = proc_tool_progame.ToolId.ToString().ToUpper();
                            eQU_COM_DEFINITION_TASKNew.OperationName = fristtaskTW0041.OperationName;
                            eQU_COM_DEFINITION_TASKNew.Equipment_Id = fristtaskTW0041.Equipment_Id;
                            eQU_COM_DEFINITION_TASKNew.EQUTask_Id = fristtaskTW0041.EQUTask_Id;
                            eQU_COM_DEFINITION_TASKNew.SubPathNo = fristtaskTW0041.SubPathNo;
                            eQU_COM_DEFINITION_TASKNew.CreateOn = DateTime.Now;
                            eQU_COM_DEFINITION_TASKNew.CreateBy = UserContext.Current.UserName;
                            //ActionSort, OperationName,EQUTask_Id,SubPathNo,Equipment_Id
                            eQU_COM_DEFINITION_TASKListAdd.Add(eQU_COM_DEFINITION_TASKNew);
                        }
                        if (fristTaskTW004 == null && fristtaskTW0041 == null)
                        {
                            ////1.增加程序和刀具，生成换刀和加工任务

                            var firstGrameNewTwo = pROC_PROGRAMsNew.Where(t => t.Id == Guid.Parse(proc_tool_progame.ProgrameId.ToUpper())).FirstOrDefault();
                            var fristTaskTW004Two = eQU_COM_DEFINITION_TASKList.OrderByDescending(t => t.CreateOn).Where(t => t.ProgramId == firstGrameNewTwo.ParentId.ToString().ToUpper() && t.Command == "TW004").FirstOrDefault();
                            var fristtaskTW0041Two = eQU_COM_DEFINITION_TASKList.OrderByDescending(t => t.CreateOn).Where(t => t.ProgramId == firstGrameNewTwo.ParentId.ToString().ToUpper() && t.Command == "TW0041").FirstOrDefault();
                            if (fristTaskTW004Two != null)
                            {
                                EQU_COM_DEFINITION_TASK eQU_COM_DEFINITION_TASKNew = new EQU_COM_DEFINITION_TASK();
                                eQU_COM_DEFINITION_TASKNew.ProgramId = proc_tool_progame.ProgrameId.ToString().ToUpper();
                                eQU_COM_DEFINITION_TASKNew.SecornSeq = firstGrameNewTwo.SecornSeq;// fristTaskTW004.SecornSeq;
                                eQU_COM_DEFINITION_TASKNew.OrderCode = proc_tool_progame.OrderCode;
                                eQU_COM_DEFINITION_TASKNew.TaskNo = fristTaskTW004Two.TaskNo + "-" + proc_tool_progame.ExecuteSort;
                                eQU_COM_DEFINITION_TASKNew.Command = fristTaskTW004Two.Command;
                                eQU_COM_DEFINITION_TASKNew.Status = "1";
                                eQU_COM_DEFINITION_TASKNew.ActionSort = (fristTaskTW004Two.ActionSort + 1) + ((proc_tool_progame.ExecuteSort.Value) * 0.01m) + ((1) * 0.01m);
                                eQU_COM_DEFINITION_TASKNew.ToolId = proc_tool_progame.ToolId.ToString().ToUpper();
                                eQU_COM_DEFINITION_TASKNew.OperationName = fristTaskTW004Two.OperationName;
                                eQU_COM_DEFINITION_TASKNew.Equipment_Id = fristTaskTW004Two.Equipment_Id;
                                eQU_COM_DEFINITION_TASKNew.EQUTask_Id = fristTaskTW004Two.EQUTask_Id;
                                eQU_COM_DEFINITION_TASKNew.SubPathNo = fristTaskTW004Two.SubPathNo;
                                eQU_COM_DEFINITION_TASKNew.CreateOn = DateTime.Now;
                                eQU_COM_DEFINITION_TASKNew.CreateBy = UserContext.Current.UserName;
                                //ActionSort, OperationName,EQUTask_Id,SubPathNo,Equipment_Id
                                eQU_COM_DEFINITION_TASKListAdd.Add(eQU_COM_DEFINITION_TASKNew);
                            }
                            if (fristtaskTW0041Two != null)
                            {
                                EQU_COM_DEFINITION_TASK eQU_COM_DEFINITION_TASKNew = new EQU_COM_DEFINITION_TASK();
                                eQU_COM_DEFINITION_TASKNew.ProgramId = proc_tool_progame.ProgrameId.ToString().ToUpper();
                                eQU_COM_DEFINITION_TASKNew.SecornSeq = fristtaskTW0041Two.SecornSeq;
                                eQU_COM_DEFINITION_TASKNew.OrderCode = proc_tool_progame.OrderCode;
                                eQU_COM_DEFINITION_TASKNew.TaskNo = fristtaskTW0041Two.TaskNo + "-" + proc_tool_progame.ExecuteSort;
                                eQU_COM_DEFINITION_TASKNew.Command = fristtaskTW0041Two.Command;
                                eQU_COM_DEFINITION_TASKNew.Status = "1";
                                eQU_COM_DEFINITION_TASKNew.ActionSort = fristtaskTW0041Two.ActionSort + ((proc_tool_progame.ExecuteSort.Value) * 0.01m) + ((2) * 0.01m);
                                eQU_COM_DEFINITION_TASKNew.ToolId = proc_tool_progame.ToolId.ToString().ToUpper();
                                eQU_COM_DEFINITION_TASKNew.OperationName = fristtaskTW0041Two.OperationName;
                                eQU_COM_DEFINITION_TASKNew.Equipment_Id = fristtaskTW0041Two.Equipment_Id;
                                eQU_COM_DEFINITION_TASKNew.EQUTask_Id = fristtaskTW0041Two.EQUTask_Id;
                                eQU_COM_DEFINITION_TASKNew.SubPathNo = fristtaskTW0041Two.SubPathNo;
                                eQU_COM_DEFINITION_TASKNew.CreateOn = DateTime.Now;
                                eQU_COM_DEFINITION_TASKNew.CreateBy = UserContext.Current.UserName;
                                //ActionSort, OperationName,EQUTask_Id,SubPathNo,Equipment_Id
                                eQU_COM_DEFINITION_TASKListAdd.Add(eQU_COM_DEFINITION_TASKNew);
                            }
                            //if (eQU_COM_DEFINITION_TASKList.Count < pROC_PROGRAMs.Count)
                            //{
                            //foreach (var item in pROC_PROGRAMsNew)
                            //    {

                            //        int sorti = 0;        
                            //        foreach (var item2 in taskList)
                            //        {
                            //            sorti++;
                            //            var fatherEquComDefintionTask = eQU_COM_DEFINITION_TASKList.Where(t => t.ProgramId == item.Id.ToString().ToUpper() && t.Command == item2.Command).FirstOrDefault();
                            //            EQU_COM_DEFINITION_TASK eQU_COM_DEFINITION_TASKNew = new EQU_COM_DEFINITION_TASK();
                            //            eQU_COM_DEFINITION_TASKNew.ProgramId = item.Id.ToString().ToUpper();
                            //            eQU_COM_DEFINITION_TASKNew.SecornSeq = item.SecornSeq;
                            //            eQU_COM_DEFINITION_TASKNew.OrderCode = item.Identifier;
                            //            eQU_COM_DEFINITION_TASKNew.TaskNo = item2.TaskNo + "-" + item.SecornSeq;
                            //            eQU_COM_DEFINITION_TASKNew.Command = item2.Command;
                            //            eQU_COM_DEFINITION_TASKNew.Status = "1";
                            //           var firstdes= taskList.OrderByDescending(t=>t.ActionSort).FirstOrDefault();
                            //            eQU_COM_DEFINITION_TASKNew.ActionSort = firstdes.ActionSort+ ((item.SecornSeq.Value) * 0.1m)+((sorti) * 0.01m);
                            //            eQU_COM_DEFINITION_TASKNew.ToolId = tools.Where(t => t.program_seq == item.sequence && t.SecornSeq == item.SecornSeq).FirstOrDefault().Id.ToString().ToUpper();
                            //            eQU_COM_DEFINITION_TASKNew.OperationName = item2.OperationName;
                            //            eQU_COM_DEFINITION_TASKNew.Equipment_Id = item2.Equipment_Id;
                            //            eQU_COM_DEFINITION_TASKNew.EQUTask_Id = item2.EQUTask_Id;
                            //            eQU_COM_DEFINITION_TASKNew.SubPathNo = item2.SubPathNo;
                            //            eQU_COM_DEFINITION_TASKNew.CreateOn = DateTime.Now;
                            //            eQU_COM_DEFINITION_TASKNew.CreateBy = UserContext.Current.UserName;
                            //            //ActionSort, OperationName,EQUTask_Id,SubPathNo,Equipment_Id
                            //            eQU_COM_DEFINITION_TASKListAdd.Add(eQU_COM_DEFINITION_TASKNew);

                            //        }

                            //        EQU_TOOL_PROGAME eQU_TOOL_PROGAME = new EQU_TOOL_PROGAME();
                            //        eQU_TOOL_PROGAME.ProgrameId = item.Id.ToString().ToUpper();
                            //        eQU_TOOL_PROGAME.OrderCode = item.Identifier;
                            //        eQU_TOOL_PROGAME.ExecuteSort = item.SecornSeq;
                            //        // //  var firstTool= tools(t => t.Identifier == taskgenerate.OrderCode&&t.program_seq== item.sequence&&t.SecornSeq==item.SecornSeq).FirstOrDefault();
                            //        eQU_TOOL_PROGAME.ToolId = tools.Where(t=>t.program_seq==item.sequence&&t.SecornSeq==item.SecornSeq).FirstOrDefault().Id.ToString().ToUpper();
                            //        eQU_TOOL_PROGAME.CreateOn = DateTime.Now;
                            //        eQU_TOOL_PROGAME.CreateBy = UserContext.Current.UserName;
                            //       // eQU_TOOL_PROGAME.ExecuteSort=
                            //        repository.DbContext.Set<EQU_TOOL_PROGAME>().Add(eQU_TOOL_PROGAME);

                            //    }
                            //}
                        }
                        proc_tool_progame.Status = "1";
                    }
                    repository.UpdateRange<EQU_TOOL_PROGAME>(pROC_TOOL_PROGAMEs, true);
                    repository.AddRange<EQU_COM_DEFINITION_TASK>(eQU_COM_DEFINITION_TASKListAdd, true);
                    repository.Update<PLAN_WORK_ORDER>(plan_work_order, true);
                    return webResponse.OK(ResponseType.Success);
                });

                // Logger.Info(LoggerType.Success, equ_TASKVM.Serialize(), webResponse.Message, msg);
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                {
                    throw new Exception(ex.Message + ex.StackTrace);
                }
                //Logger.Info(LoggerType.Exception, equ_TASKVM.Serialize(), webResponse.Message, msg);
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {
                //  Logger.Info(LoggerType.Login, equ_TASKVM.Serialize(), webResponse.Message, msg);
            }
        }
        public async Task<WebResponseContent> Equ_MarkTask(Equ_TaskReceive equ_TASKVM, string type = "")
        {
            equ_TASKVM.Status = "6";//弃用

            string msg = string.Empty;
            try
            {
                EQU_COM_DEFINITION_TASK eQU_COM_DEFINITION_TASK = null;
                List<EQU_COM_DEFINITION_TASK> eQU_COM_DEFINITION_TASKList = new List<EQU_COM_DEFINITION_TASK>();
                PROC_PROGRAM pROC_PROGRAM = null;
                var taskNo = equ_TASKVM.TaskNo;
                EQU_EQUIPMENT equmlAction = null;
                PLAN_WORK_ORDER plan_work_order = null;
                if (equ_TASKVM.Status == "6")//弃用
                {
                    if (equ_TASKVM.Id != null)
                    {
                        pROC_PROGRAM = await repository.FindAsyncFirst<PROC_PROGRAM>(t => t.Id == Guid.Parse(equ_TASKVM.Id));
                        eQU_COM_DEFINITION_TASKList = await repository.FindAsync<EQU_COM_DEFINITION_TASK>(t => t.OrderCode == pROC_PROGRAM.Identifier && t.ProgramId == pROC_PROGRAM.Id.ToString());

                        if (equ_TASKVM.DisuseState == "1")
                        {
                            pROC_PROGRAM.DisuseState = "0";//启用
                            foreach (var itemDefinitionTask in eQU_COM_DEFINITION_TASKList)
                            {
                                itemDefinitionTask.Status = "5";
                                itemDefinitionTask.ExecuteEnd = null;
                                itemDefinitionTask.ActionEquipmentId = null;
                                itemDefinitionTask.ExecuteStart = null;
                            }
                        }
                        else
                        {
                            pROC_PROGRAM.DisuseState = "1";//弃用

                            foreach (var itemDefinitionTask in eQU_COM_DEFINITION_TASKList)
                            {
                                itemDefinitionTask.Status = equ_TASKVM.Status;
                                itemDefinitionTask.ExecuteEnd = null;
                                itemDefinitionTask.ActionEquipmentId = null;
                                itemDefinitionTask.ExecuteStart = null;
                            }
                        }
                    }


                }



                WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
                {
                    if (eQU_COM_DEFINITION_TASK != null)
                    {
                        repository.Update<EQU_COM_DEFINITION_TASK>(eQU_COM_DEFINITION_TASK, true);
                    }
                    if (eQU_COM_DEFINITION_TASKList.Count > 0)
                    {
                        foreach (var item in eQU_COM_DEFINITION_TASKList)
                        {
                            repository.Update<EQU_COM_DEFINITION_TASK>(item, true);
                        }
                    }

                    if (pROC_PROGRAM != null)
                    {
                        repository.Update<PROC_PROGRAM>(pROC_PROGRAM, true);
                    }
                    return webResponse.OK(ResponseType.Success);
                });

                Logger.Info(LoggerType.Success, equ_TASKVM.Serialize(), webResponse.Message, msg);
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                {
                    throw new Exception(ex.Message + ex.StackTrace);
                }
                Logger.Info(LoggerType.Exception, equ_TASKVM.Serialize(), webResponse.Message, msg);
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {
                Logger.Info(LoggerType.Login, equ_TASKVM.Serialize(), webResponse.Message, msg);
            }
        }
        public async Task<WebResponseContent> Equ_MarkTask(Equ_TaskReceive equ_TASKVM)
        {
            equ_TASKVM.Status = "6";//弃用
            string msg = string.Empty;
            try
            {
                EQU_COM_DEFINITION_TASK eQU_COM_DEFINITION_TASK = null;
                List<EQU_COM_DEFINITION_TASK> eQU_COM_DEFINITION_TASKList = new List<EQU_COM_DEFINITION_TASK>();
                PROC_PROGRAM pROC_PROGRAM = null;
                var taskNo = equ_TASKVM.TaskNo;
                EQU_EQUIPMENT equmlAction = null;
                PLAN_WORK_ORDER plan_work_order = null;
                if (equ_TASKVM.Status == "6")//弃用
                {
                    eQU_COM_DEFINITION_TASK = await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(t => t.TaskNo == taskNo);
                    if (eQU_COM_DEFINITION_TASK == null)
                    {
                        Logger.Info(LoggerType.Login, "此次执行任务没有设备", webResponse.Message, msg);
                        return webResponse.Error("此次执行任务没有设备");
                    }

                    eQU_COM_DEFINITION_TASK.Status = equ_TASKVM.Status;
                    eQU_COM_DEFINITION_TASK.ExecuteEnd = null;
                    eQU_COM_DEFINITION_TASK.ActionEquipmentId = null;
                    eQU_COM_DEFINITION_TASK.ExecuteStart = null;

                    if ((eQU_COM_DEFINITION_TASK.ProgramId != ""))
                    {
                        pROC_PROGRAM = await repository.FindAsyncFirst<PROC_PROGRAM>(t =>
                            t.Identifier == eQU_COM_DEFINITION_TASK.OrderCode &&
                            t.Id == Guid.Parse(eQU_COM_DEFINITION_TASK.ProgramId));
                        if (pROC_PROGRAM.DisuseState == "1")
                        {

                        }
                        else
                        {
                            pROC_PROGRAM.DisuseState = "1"; //弃用
                        }

                    }
                }



                WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
                {
                    if (eQU_COM_DEFINITION_TASK != null)
                    {
                        repository.Update<EQU_COM_DEFINITION_TASK>(eQU_COM_DEFINITION_TASK, true);
                    }
                    if (eQU_COM_DEFINITION_TASKList.Count > 0)
                    {
                        foreach (var item in eQU_COM_DEFINITION_TASKList)
                        {
                            repository.Update<EQU_COM_DEFINITION_TASK>(item, true);
                        }
                    }

                    if (pROC_PROGRAM != null)
                    {
                        repository.Update<PROC_PROGRAM>(pROC_PROGRAM, true);
                    }
                    return webResponse.OK(ResponseType.Success);
                });

                Logger.Info(LoggerType.Success, equ_TASKVM.Serialize(), webResponse.Message, msg);
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                {
                    throw new Exception(ex.Message + ex.StackTrace);
                }
                Logger.Info(LoggerType.Exception, equ_TASKVM.Serialize(), webResponse.Message, msg);
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {
                Logger.Info(LoggerType.Login, equ_TASKVM.Serialize(), webResponse.Message, msg);
            }
        }

        //taskcontinue
        public async Task<WebResponseContent> TaskContinue(Equ_TaskReceive equ_TASKVM)
        {
            Equ_TASKVM equ_TASKVM1 = new Equ_TASKVM();
            string msg = string.Empty;
            var isConnectUpdate1 = IsIpConnect("192.168.1.160");
            if (isConnectUpdate1 == false)
            {
                webResponse.Data = $"192.168.1.160 ping不通！";
                return webResponse.Error($"192.168.1.1 ping不通！");
            }

            try
            {
                EQU_COM_DEFINITION_TASK eQU_COM_DEFINITION_TASK = null;
                List<EQU_COM_DEFINITION_TASK> eQU_COM_DEFINITION_TASKList = new List<EQU_COM_DEFINITION_TASK>();
                PROC_PROGRAM pROC_PROGRAM = null;
                var taskNo = equ_TASKVM.TaskNo;
                EQU_EQUIPMENT equmlAction = null;
                PLAN_WORK_ORDER plan_work_order = null;
                eQU_COM_DEFINITION_TASK = await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(t => t.TaskNo == equ_TASKVM.TaskNo);
                Guid equipment_Id = Guid.Parse(eQU_COM_DEFINITION_TASK.Equipment_Id.ToString());

                var equmlcnc = await repository.FindAsyncFirst<EQU_EQUIPMENT>(t => t.Id == equipment_Id);
                equ_TASKVM1.Command = "TW00411";
                equ_TASKVM1.Unit = equmlcnc.unit == null ? 1 : equmlcnc.unit.Value;

                webResponse.Data = equ_TASKVM1.Serialize();
                //MQ_Send
                SendTaskToMQ(equmlcnc, eQU_COM_DEFINITION_TASK);


                //WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
                //{
                //    if (eQU_COM_DEFINITION_TASK != null)
                //    {
                //        repository.Update<EQU_COM_DEFINITION_TASK>(eQU_COM_DEFINITION_TASK, true);
                //    }
                //    if (eQU_COM_DEFINITION_TASKList.Count > 0)
                //    {
                //        foreach (var item in eQU_COM_DEFINITION_TASKList)
                //        {
                //            repository.Update<EQU_COM_DEFINITION_TASK>(item, true);
                //        }
                //    }

                //    if (pROC_PROGRAM != null)
                //    {
                //        repository.Update<PROC_PROGRAM>(pROC_PROGRAM, true);
                //    }
                //    return webResponse.OK(ResponseType.Success);
                //});

                Logger.Info(LoggerType.Success, equ_TASKVM.Serialize(), webResponse.Message, msg);
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;

                Logger.Info(LoggerType.Exception, equ_TASKVM.Serialize(), webResponse.Message, msg);
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {
                Logger.Info(LoggerType.Login, equ_TASKVM.Serialize(), webResponse.Message, msg);
            }

        }
        /// <summary>
        /// Ready
        /// </summary>
        /// <param name="taskNo"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<WebResponseContent> Equ_SendTASKReady(int orderCode, decimal width)
        {
            var iNTE_SHELVES = repository.DbContext.Set<INTE_SHELVES>().ToList();
            decimal maxWidth = 1000;
            string msg = string.Empty;
            var orderCodeStr = orderCode.ToString();

            var planWork = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.OrderCode.Contains("-"+orderCodeStr));
            if (planWork == null)
            {
                Logger.Info(LoggerType.Login, $"{orderCode}没找到", webResponse.Message, msg);
                return webResponse.Error($"{orderCode}没找到");
            }
            if (planWork != null && planWork.width >= maxWidth)
            {
                Logger.Info(LoggerType.Login, $"工件宽{width}与定义工件宽不符", webResponse.Message, msg);
                return webResponse.Error($"工件宽{width}与定义工件宽不符");
            }
            var taskNo = string.Empty;
            var eQU_COM_DEFINITION_TASKtaskNoTASK001 = await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(t =>
                t.OrderCode == planWork.OrderCode && t.Command == "TASK001" && (t.Status == "1" || t.Status == "5"));
            if (eQU_COM_DEFINITION_TASKtaskNoTASK001 != null)
            {
                Logger.Info(LoggerType.Login, $"工件TASK001没有完成或者没写Rfid", webResponse.Message, msg);
                return webResponse.Error($"工件TASK001没有完成或者没写Rfid");
            }
            var eQU_COM_DEFINITION_TASKtaskNo = await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(t =>
             t.OrderCode == planWork.OrderCode && t.Command == "TW001" && (t.Status == "1" || t.Status == "5"));
            if (eQU_COM_DEFINITION_TASKtaskNo != null)
            {
                taskNo = eQU_COM_DEFINITION_TASKtaskNo.TaskNo;
            }
            var sequence = int.Parse(SplitEx(taskNo, taskNo.Split("-").Length - 1));
            //1.获取任务信息 没有设备执行任务
            var eQU_COM_DEFINITION_TASK = await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(t => t.TaskNo == taskNo && t.ActionEquipmentId == null);
            if (eQU_COM_DEFINITION_TASK == null)
            {
                Logger.Info(LoggerType.Login, "此次执行任务以有设备", webResponse.Message, msg);
                return webResponse.Error("此次执行任务以有设备");
            }
            var lastEquComDefinitionTask = await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(t => t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode && t.ActionSort ==
                (eQU_COM_DEFINITION_TASK.ActionSort - 1));
            Guid equipment_Id = Guid.Parse(eQU_COM_DEFINITION_TASK.Equipment_Id.ToString());
            Guid eQUTask_Id = Guid.Parse(eQU_COM_DEFINITION_TASK.EQUTask_Id);
            var equmlcnc = await repository.FindAsyncFirst<EQU_EQUIPMENT>(t => t.Id == equipment_Id);
            var plan_work_order = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode);

            var orderid = plan_work_order.Order_Id.ToString();
            MANU_EXECUTION manuExecution = await repository.FindAsyncFirst<MANU_EXECUTION>(t => t.Order_Id == orderid);
            var op = await repository.FindAsyncFirst<PROC_OPERATION>(t => t.Identifier == eQU_COM_DEFINITION_TASK.OperationName);
            MANU_SUMMARY manuSummary = await repository.FindAsyncFirst<MANU_SUMMARY>(t => t.WorkOrderId == orderid && t.OperationId == op.Identifier);
            var productId = Guid.Parse(plan_work_order.ProductId);
            PROC_MATERIAL piece = repository.Find<PROC_MATERIAL>(t => t.Id == productId)
                .FirstOrDefault();
            var equ_tool = await repository.FindAsyncFirst<EQU_TOOL>(t => t.Identifier.StartsWith(eQU_COM_DEFINITION_TASK.OrderCode) && t.program_seq == sequence);
            var equ_task = await repository.FindAsyncFirst<EQU_TASK>(t => t.EQUTask_Id == eQUTask_Id);
            var pROC_PROGRAMs = await repository.FindAsync<PROC_PROGRAM>(t => t.Identifier == eQU_COM_DEFINITION_TASK.OrderCode);
            var pROC_PROGRAM = pROC_PROGRAMs.Where(t => t.sequence == sequence).FirstOrDefault();// await repository.FindAsyncFirst<PROC_PROGRAM>(t => t.Identifier == eQU_COM_DEFINITION_TASK.OrderCode&&t.sequence== sequence);
            if (equ_tool != null && equ_tool.location == null)
            {
                Logger.Info(LoggerType.Login, "此次执行刀具没入库", webResponse.Message, msg);
                return webResponse.Error("此次执行刀具没入库");
            }
            try
            {

                //2.设备接收任务 2.1设备待机，2.2设备有任务指令 2.3路径无干涩

                var EQU_COM_DEFINITION_TASKml = repository.Find<EQU_COM_DEFINITION_TASK>(t => t.TaskNo == taskNo).FirstOrDefault();
                var eQU_EQUIPMENTs = repository.Find<EQU_EQUIPMENT>(t => t.EquCommds != null && t.StateCode == 1 && t.EquCommds.Contains(EQU_COM_DEFINITION_TASKml.Command)).ToList();
                while (eQU_EQUIPMENTs.Count == 0)
                {
                    eQU_EQUIPMENTs = repository.Find<EQU_EQUIPMENT>(t => t.EquCommds != null && t.StateCode == 1 && t.EquCommds.Contains(EQU_COM_DEFINITION_TASKml.Command)).ToList();
                    if (eQU_EQUIPMENTs.Count > 0)
                    {
                        break;
                    }
                    Thread.Sleep(1000);
                }
                if (eQU_EQUIPMENTs.Count == 0)
                {

                    Logger.Info(LoggerType.Login, "此次执行任务无空闲设备", webResponse.Message, msg);
                    return webResponse.Error("此次执行任务无空闲设备");
                }
                var equ_TASKVM1 = EquTaskvm1(equ_task, equmlcnc, eQU_COM_DEFINITION_TASK, plan_work_order, equ_tool, pROC_PROGRAM, pROC_PROGRAMs, piece);
                webResponse.Data = equ_TASKVM1.Serialize().ToString();
                //webResponse.ExData = "[" + equ_TASKVM1.Serialize().ToString() + "]";
                WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
                {
                    SetEquXY(eQU_EQUIPMENTs);
                    foreach (var item in eQU_EQUIPMENTs)
                    {

                        EquComDefinitionTask(EQU_COM_DEFINITION_TASKml, item, equ_tool, iNTE_SHELVES, ((int)StatusAction.Executing).ToString(), equmlcnc);
                        //   item.StateCode = 0;// 0：自动运行; 1：待机; 2：正常停机; 3：故障停机; 4：待料;5：满料；
                        var arryTaskCode = item.EquCommds.Split(",").ToArray();
                        int iscount = arryTaskCode.Where(t => t.StartsWith(EQU_COM_DEFINITION_TASKml.Command)).Count();
                        if (iscount > 0)
                        {
                            repository.Update<EQU_EQUIPMENT>(item, true);
                        }
                        else
                        {
                            return new WebResponseContent().Error("此次执行任务无设备");
                        }
                    }
                    ManuSummary(ref manuSummary, piece, orderid, EQU_COM_DEFINITION_TASKml);
                    ManuExecution(ref manuExecution, piece, orderid, EQU_COM_DEFINITION_TASKml, lastEquComDefinitionTask, plan_work_order);
                    PlanWorkOrder(ref plan_work_order, EQU_COM_DEFINITION_TASKml);

                    repository.Update<EQU_COM_DEFINITION_TASK>(EQU_COM_DEFINITION_TASKml, true);
                    return webResponse.OK(ResponseType.Success);
                });
                //判断事务是否执行成功
                if (!webResponse1.Status)
                {
                    return new WebResponseContent().Error("返回消息");

                }

                //MQ_Send

                SendTaskToMQ(equmlcnc, EQU_COM_DEFINITION_TASKml);

                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                {
                    throw new Exception(ex.Message + ex.StackTrace);
                }
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {

                Logger.Info(LoggerType.Login, eQU_COM_DEFINITION_TASK.Serialize(), webResponse.Message, msg);
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="taskNo"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<WebResponseContent> Equ_SendTASK(string taskNo, IMapper _mapper)
        {
            var context = VOL.Core.Utilities.HttpContext.Current;
            var UserIP = context.GetUserIp()?.Replace("::ffff:", "");
            var ServiceIP = context.Connection.LocalIpAddress.MapToIPv4().ToString() + ":" + context.Connection.LocalPort;
            var serviceIPSend = QueryInteConfigure("ServiceIP");
            var serviceIP = "192.168.110.183:8088";
            //if (serviceIPSend != null)
            //{
            //    serviceIP = serviceIPSend.ConfigureParam;
            //}
            //if (ServiceIP != serviceIP)
            //{
            //    return webResponse.Error(UserIP + "____" + ServiceIP);
            //}
            string msg = string.Empty;
            var iNTE_SHELVES = repository.DbContext.Set<INTE_SHELVES>().ToList();
            var sequence = int.Parse(SplitEx(taskNo, taskNo.Split("-").Length - 1));
            //1.获取任务信息 没有设备执行任务
            var eQU_COM_DEFINITION_TASK = await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(t => t.TaskNo == taskNo && t.ActionEquipmentId == null);
            if (eQU_COM_DEFINITION_TASK == null)
            {
                Logger.Info(LoggerType.Login, "此次执行任务以有设备", webResponse.Message, msg);
                return webResponse.Error("此次执行任务以有设备");
            }
            //栅栏门
            #region
            var planw = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(w => w.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode);
            var equml = await repository.FindAsyncFirst<EQU_EQUIPMENT>(t => t.Description == planw.processing_machines && t.FenceGate == "1");
            if (equml != null)
            {
                Logger.Info(LoggerType.Login, $"设备栅栏门打开【{equml.Description}】", $"设备栅栏门打开【{equml.Description}】", $"设备栅栏门打开【{equml.Description}】");
                return webResponse.Error($"设备栅栏门打开【{equml.Description}】");
            }
            #endregion
            //拦截
            #region
            var interceptionList =await repository.FindAsync<MANU_PROCESS_INTERCEPTION>(t => t.Status == "1" );
            var condition = new AndCondition();

            foreach (var item in interceptionList)
            {
                condition
                    .AddCondition(new TextCondition("工序", $"{eQU_COM_DEFINITION_TASK.OperationName}",
                               ConditionOperator.Equal, item.OperationId))
                    .AddCondition(new TextCondition("工单", $"{eQU_COM_DEFINITION_TASK.OrderCode}",
                               ConditionOperator.Equal, item.Order_Id));
            }
            if (interceptionList.Count > 0)
            {
                var builder = new ConditionBuilder().SetRoot(condition);
                var valtree = builder.VisualizeExpressionTree();

                // 实际拦截逻辑
                if (builder.Evaluate())
                {
                    // 执行拦截操作
                    return webResponse.Error(">>> 触发拦截条件，执行拦截操作! <<<" + Environment.NewLine + valtree);
                    //  Console.WriteLine("\n>>> 触发拦截条件，执行拦截操作! <<<");
                }
                //else
                //{
                //    Console.WriteLine("\n>>> 条件未满足，继续执行流程 <<<");

                //}
            }
            #endregion


            //设备使能锁
            List<string> emptyEqusEable = null;// new List<string>() { "JCR_001", "SLK_001",  "FNK_001", "SLL_001" };//SLK_002
            var equsEableLock = QueryInteConfigure("EqusEableLock");
            if (equsEableLock != null)
            {
                emptyEqusEable = equsEableLock.ConfigureParam.Split(",").ToList();
            }

            if (equsEableLock != null)
            {
                var Equs = await repository.FindAsync<EQU_EQUIPMENT>(t => emptyEqusEable.Contains(t.EquipmentCode));
                if (Equs != null)
                {
                    foreach (var itemEquipment in Equs)
                    {
                        if (itemEquipment.IsEnable != true)
                        {
                            Logger.Info(LoggerType.Login, "设备未就绪", webResponse.Message, "设备未就绪");
                            webResponse.Data = $"设备未就绪:" + itemEquipment.EquipmentNameZH; ;
                            return webResponse.Error($"设备未就绪:" + itemEquipment.EquipmentNameZH);
                        }
                    }
                }

            }
            //设备锁
            List<string> emptyEqus = null;// new List<string>() { "JCR_001", "SLK_001",  "FNK_001", "SLL_001" };//SLK_002
            var equsLock = QueryInteConfigure("EqusLock");
            if (equsLock != null)
            {
                emptyEqus = equsLock.ConfigureParam.Split(",").ToList();
            }
            //1.获取设备信息 没有设备执行任务
            if (equsLock != null)
            {
                var Equs = await repository.FindAsync<EQU_EQUIPMENT>(t => emptyEqus.Contains(t.EquipmentCode));
                if (Equs != null)
                {
                    foreach (var itemEquipment in Equs)
                    {
                        if (itemEquipment.StateCode != 1)
                        {
                            Logger.Info(LoggerType.Login, "设备正运行", webResponse.Message, "设备正运行");
                            //   msgError += "设备正运行:" + itemEquipment.EquipmentNameZH;
                            webResponse.Data = $"设备正运行:" + itemEquipment.EquipmentNameZH; ;
                            return webResponse.Error($"设备正运行:" + itemEquipment.EquipmentNameZH);
                        }
                    }
                }

            }

            //设备任务锁
            List<string> emptyEqusTasks = null;// new List<string>() TW001,TW002,TW003,TW0031,TW0032,TW004,TW005,TW006,TW007
            var equsTaskLock = QueryInteConfigure("EqusLockTask");
            if (equsTaskLock != null)
            {
                emptyEqusTasks = equsTaskLock.ConfigureParam.Split(",").ToList();
            }
            if (equsTaskLock != null)
            {
                var countcmdTask = await repository.FindAsync<EQU_COM_DEFINITION_TASK>(t => emptyEqusTasks.Contains(t.Command) && (t.Status == "2"));
                if (countcmdTask.Count == 0)
                { }
                else if (countcmdTask.Count > 0 && countcmdTask.Count < 2)
                {
                    foreach (var t in countcmdTask)
                    {
                        var currPlanOrder = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(w => w.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode);
                        var otherPlanOrder = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(w => w.OrderCode == t.OrderCode);
                        string pattern = @"\d+"; // 匹配一个或多个数字
                        Match matchCurr = Regex.Match(currPlanOrder.processing_machines, pattern);
                        Match matchOther = Regex.Match(otherPlanOrder.processing_machines, pattern);
                        if (matchCurr.Success && matchOther.Success)
                        {
                            if (matchCurr.Value == matchOther.Value)
                            {
                                Logger.Info(LoggerType.Login, "【" + taskNo + "】任务排队中", webResponse.Message, "任务排队中");
                                return webResponse.Error("任务排队中【同一台设备】");
                            }

                            if (Math.Abs(int.Parse(matchCurr.Value) - int.Parse(matchOther.Value)) == 1)
                            {
                                Logger.Info(LoggerType.Login, "设备与设备有干涩");
                                return webResponse.Error("设备与设备有干涩");
                            }
                        }
                        //不同工单可以同时上料，换刀
                        if (t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode && (t.Command == "TW004" || t.Command == "TW003") && (eQU_COM_DEFINITION_TASK.Command == "TW004" || eQU_COM_DEFINITION_TASK.Command == "TW003"))
                        {
                            Logger.Info(LoggerType.Login, "【" + taskNo + "】任务排队中", webResponse.Message, "任务排队中");
                            return webResponse.Error("任务排队中【一个工单同时上料，换刀】");
                        }
                        else if (t.OrderCode != eQU_COM_DEFINITION_TASK.OrderCode && (t.Command == "TW0031") && (eQU_COM_DEFINITION_TASK.Command == "TW003"))//不同工单可以同时 上料 上刀
                        {
                        }
                        else if (t.OrderCode != eQU_COM_DEFINITION_TASK.OrderCode && (t.Command == "TW003") && (eQU_COM_DEFINITION_TASK.Command == "TW0031"))//不同工单可以同时 上料 上刀
                        {
                        }
                        else if (t.OrderCode != eQU_COM_DEFINITION_TASK.OrderCode && (t.Command == "TW004") && (eQU_COM_DEFINITION_TASK.Command == "TW003"))  //不同工单可以同时上料，换刀
                        {
                        }
                        else if (t.OrderCode != eQU_COM_DEFINITION_TASK.OrderCode && (t.Command == "TW003") && (eQU_COM_DEFINITION_TASK.Command == "TW004"))  //不同工单可以同时上料，换刀
                        {
                        }
                        else if (t.OrderCode != eQU_COM_DEFINITION_TASK.OrderCode && (t.Command == "TW0032") && (eQU_COM_DEFINITION_TASK.Command == "TW004"))//不同工单可以同时 测量 换刀
                        {
                        }
                        else if (t.OrderCode != eQU_COM_DEFINITION_TASK.OrderCode && (t.Command == "TW004") && (eQU_COM_DEFINITION_TASK.Command == "TW0032"))//不同工单可以同时 测量 换刀
                        {
                        }
                        else if (t.OrderCode != eQU_COM_DEFINITION_TASK.OrderCode && (t.Command == "TW003201") && (eQU_COM_DEFINITION_TASK.Command == "TW004"))//不同工单可以同时 分中 换刀
                        {
                        }
                        else if (t.OrderCode != eQU_COM_DEFINITION_TASK.OrderCode && (t.Command == "TW004") && (eQU_COM_DEFINITION_TASK.Command == "TW003201"))//不同工单可以同时 分中 换刀
                        {
                        }
                        else if (t.OrderCode != eQU_COM_DEFINITION_TASK.OrderCode && (t.Command == "TW003202") && (eQU_COM_DEFINITION_TASK.Command == "TW004"))//不同工单可以同时 找平 换刀
                        {
                        }
                        else if (t.OrderCode != eQU_COM_DEFINITION_TASK.OrderCode && (t.Command == "TW004") && (eQU_COM_DEFINITION_TASK.Command == "TW003202"))//不同工单可以同时 找平 换刀
                        {
                        }

                        else if (t.OrderCode != eQU_COM_DEFINITION_TASK.OrderCode && (t.Command == "TW004") && (eQU_COM_DEFINITION_TASK.Command == "TW003"))
                        {
                        }
                        else if (t.OrderCode != eQU_COM_DEFINITION_TASK.OrderCode && (t.Command == "TW003") && (eQU_COM_DEFINITION_TASK.Command == "TW004"))
                        {
                        }
                        else if (t.OrderCode != eQU_COM_DEFINITION_TASK.OrderCode && (eQU_COM_DEFINITION_TASK.Command == "TW0041"))
                        {
                        }
                        else
                        {
                            Logger.Info(LoggerType.Login, "【" + taskNo + "】任务排队中", webResponse.Message, "任务排队中");
                            return webResponse.Error("任务排队中");
                        }
                    }


                }
                else
                {
                    Logger.Info(LoggerType.Login, "【" + taskNo + "】任务排队中", webResponse.Message, "任务排队中");
                    return webResponse.Error("任务排队中");
                }

            }

            var lastEquComDefinitionTask = await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(t => t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode && t.ActionSort ==
                (eQU_COM_DEFINITION_TASK.ActionSort - 1));
            Guid equipment_Id = Guid.Parse(eQU_COM_DEFINITION_TASK.Equipment_Id.ToString());
            Guid eQUTask_Id = Guid.Parse(eQU_COM_DEFINITION_TASK.EQUTask_Id);
            var equmlcnc = await repository.FindAsyncFirst<EQU_EQUIPMENT>(t => t.Id == equipment_Id);
            var plan_work_order = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode);
            var orderid = plan_work_order.Order_Id.ToString();

            var op = await repository.FindAsyncFirst<PROC_OPERATION>(t => t.Identifier == eQU_COM_DEFINITION_TASK.OperationName);
            MANU_SUMMARY manuSummary = await repository.FindAsyncFirst<MANU_SUMMARY>(t => t.WorkOrderId == orderid && t.OperationId == op.Identifier);
            MANU_EXECUTION manuExecution = await repository.FindAsyncFirst<MANU_EXECUTION>(t => t.Order_Id == orderid);
            var productId = Guid.Parse(plan_work_order.ProductId);
            PROC_MATERIAL piece = repository.Find<PROC_MATERIAL>(t => t.Id == productId)
                .FirstOrDefault();

            var equ_tool = await repository.FindAsyncFirst<EQU_TOOL>(t => t.Identifier.StartsWith(eQU_COM_DEFINITION_TASK.OrderCode) && t.program_seq == sequence);
            var equ_task = await repository.FindAsyncFirst<EQU_TASK>(t => t.EQUTask_Id == eQUTask_Id);
            var pROC_PROGRAMs = await repository.FindAsync<PROC_PROGRAM>(t => t.Identifier == eQU_COM_DEFINITION_TASK.OrderCode);
            var pROC_PROGRAM = pROC_PROGRAMs.Where(t => t.sequence == sequence).FirstOrDefault();// await repository.FindAsyncFirst<PROC_PROGRAM>(t => t.Identifier == eQU_COM_DEFINITION_TASK.OrderCode&&t.sequence== sequence);
            if (equ_tool != null && equ_tool.location == null)
            {
                Logger.Info(LoggerType.Login, "此次执行刀具没入库", webResponse.Message, msg);
                return webResponse.Error("此次执行刀具没入库");
            }
            if (equ_tool != null && equ_tool.location == 0)
            {
                Logger.Info(LoggerType.Login, "此次执行刀具没入库", webResponse.Message, msg);
                return webResponse.Error("此次执行刀具没入库");
            }
            EQU_COM_DEFINITION_TASK EQU_COM_DEFINITION_TASKml = null;
            try
            {
                //2.设备接收任务 2.1设备待机，2.2设备有任务指令 2.3路径无干涩

                EQU_COM_DEFINITION_TASKml = repository.Find<EQU_COM_DEFINITION_TASK>(t => t.TaskNo == taskNo).FirstOrDefault();
                if (EQU_COM_DEFINITION_TASKml.Command == "TW0041")//换刀
                {
                    repository.Update<EQU_TOOL>(equ_tool, true);
                }
                var eQU_EQUIPMENTs = repository.Find<EQU_EQUIPMENT>(t => t.EquCommds != null && t.StateCode == 1 && t.EquCommds.Contains(EQU_COM_DEFINITION_TASKml.Command)).ToList();
                if (eQU_EQUIPMENTs.Count == 0)
                {

                    Logger.Info(LoggerType.Login, "此次执行任务无空闲设备", webResponse.Message, msg);
                    return webResponse.Error("此次执行任务无空闲设备");
                }
                var equCurrentOrder = repository.Find<EQU_EQUIPMENT>(t => t.Id == Guid.Parse(EQU_COM_DEFINITION_TASKml.Equipment_Id.ToString().ToUpper()))
                      .FirstOrDefault();
                if (equCurrentOrder != null)
                {
                    equCurrentOrder.CurrentOrder = EQU_COM_DEFINITION_TASKml.OrderCode;
                }
                var equ_TASKVM1 = EquTaskvm1(equ_task, equmlcnc, eQU_COM_DEFINITION_TASK, plan_work_order, equ_tool, pROC_PROGRAM, pROC_PROGRAMs, piece);
                webResponse.Data = equ_TASKVM1.Serialize().ToString();
                //webResponse.ExData = "[" + equ_TASKVM1.Serialize().ToString() + "]";
                WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
                {
                    SetEquXY(eQU_EQUIPMENTs);
                    foreach (var item in eQU_EQUIPMENTs)
                    {
                        EquComDefinitionTask(EQU_COM_DEFINITION_TASKml, item, equ_tool, iNTE_SHELVES, ((int)StatusAction.Executing).ToString(), equmlcnc);
                        //  item.StateCode = 0;// 0：自动运行; 1：待机; 2：正常停机; 3：故障停机; 4：待料;5：满料；
                        var arryTaskCode = item.EquCommds.Split(",").ToArray();
                        int iscount = arryTaskCode.Where(t => t.StartsWith(EQU_COM_DEFINITION_TASKml.Command)).Count();
                        if (iscount > 0)
                        {
                            repository.Update<EQU_EQUIPMENT>(item, true);
                        }
                        else
                        {
                            return new WebResponseContent().Error("此次执行任务无设备");
                        }
                    }
                    ManuSummary(ref manuSummary, piece, orderid, EQU_COM_DEFINITION_TASKml);
                    ManuExecution(ref manuExecution, piece, orderid, EQU_COM_DEFINITION_TASKml, lastEquComDefinitionTask, plan_work_order);
                    PlanWorkOrder(ref plan_work_order, EQU_COM_DEFINITION_TASKml);
                    EQU_COM_DEFINITION_TASKml.Description = "";
                    repository.Update<EQU_COM_DEFINITION_TASK>(EQU_COM_DEFINITION_TASKml, true);
                    repository.Update<EQU_EQUIPMENT>(equCurrentOrder, true);
                    if (piece != null && EQU_COM_DEFINITION_TASKml.Command == "TW003")//上料
                    {
                        piece.StorageState = "未入库";
                        piece.SHELVES_Id = null;
                        repository.Update<PROC_MATERIAL>(piece, true);
                    }
                    return webResponse.OK(ResponseType.Success);
                });
                //判断事务是否执行成功
                if (!webResponse1.Status)
                {
                    return new WebResponseContent().Error("返回消息");
                }

                if (EQU_COM_DEFINITION_TASKml != null)
                {
                    EQU_COM_DEFINITION_TASK_RECORD taskRecord = new EQU_COM_DEFINITION_TASK_RECORD();
                    taskRecord.EQUTask_Id = EQU_COM_DEFINITION_TASKml.EQUTask_Id;
                    taskRecord.Equipment_Id = EQU_COM_DEFINITION_TASKml.Equipment_Id;
                    taskRecord.SendLog = webResponse.Data.ToString();
                    taskRecord.ComDefintion_TaskId = EQU_COM_DEFINITION_TASKml.ComDefintion_TaskId.ToString().ToUpper();
                    repository.DbContext.Set<EQU_COM_DEFINITION_TASK_RECORD>().Add(taskRecord);

                    var EQU_COM_DEFINITION_TASKLog = repository.Find<EQU_COM_DEFINITION_TASK>(t => t.TaskNo == taskNo)
                   .FirstOrDefault();
                    if (EQU_COM_DEFINITION_TASKLog != null)
                    {
                        var tASK_LOGs = _mapper.Map<EQU_COM_DEFINITION_TASK_LOG>(EQU_COM_DEFINITION_TASKLog);
                        repository.DbContext.Set<EQU_COM_DEFINITION_TASK_LOG>().AddRange(tASK_LOGs);
                    }
                    repository.DbContext.SaveChanges();

                }
                var taskList = repository.Find<EQU_COM_DEFINITION_TASK>(t => t.OrderCode == eQU_COM_DEFINITION_TASK.OrderCode);
                foreach (var item in taskList)
                {
                    if (EQU_COM_DEFINITION_TASKml.TaskNo == item.TaskNo)
                    {

                    }
                    else
                    {
                        if (EQU_COM_DEFINITION_TASKml.Command == "TW006")
                        {
                            item.IsCurrentOrderCode = "0";
                        }
                        else
                        {
                            item.IsCurrentOrderCode = "1";
                        }

                        repository.DbContext.Update<EQU_COM_DEFINITION_TASK>(item);
                        repository.DbContext.SaveChanges();
                    }

                }


                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                {
                    throw new Exception(ex.Message + ex.StackTrace);
                }
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {
                if (webResponse.Status == true && EQU_COM_DEFINITION_TASKml != null)
                {
                    taskQueue.Enqueue(() =>
                    //MQ_Send
                    SendTaskToMQ(equmlcnc, EQU_COM_DEFINITION_TASKml)
                    );

                    while (taskQueue.Count > 0)
                    {
                        Action task = taskQueue.Dequeue();
                        await Task.Run(task); // 在新线程中执行任务，保持主线程继续处理队列中的下一个任务。
                    }
                    ////MQ_Send
                    //SendTaskToMQ(equmlcnc, EQU_COM_DEFINITION_TASKml);
                    Logger.Info(LoggerType.Add, eQU_COM_DEFINITION_TASK.Serialize(), webResponse.Message, webResponse.Data.ToString());
                }

            }


        }
        void SendTaskToMQ(EQU_EQUIPMENT equmlcnc, EQU_COM_DEFINITION_TASK EQU_COM_DEFINITION_TASKml)
        {
            //MQ_Send
            var inteconfig = QueryInteConfigure("MQ_Send");
            if (inteconfig != null)
            {
                if (EQU_COM_DEFINITION_TASKml.Command == "TASK001" || EQU_COM_DEFINITION_TASKml.Command == "TW001")
                {

                    if (equmlcnc.EquipmentNo == "1" && EQU_COM_DEFINITION_TASKml.Command != "TASK001")
                    {
                        MQHelper.MQSendMsg(webResponse.Data.ToString(), MQqueue.Equ_SendTask_1.ToString());
                    }
                    else if (equmlcnc.EquipmentNo == "2" && EQU_COM_DEFINITION_TASKml.Command != "TASK001")
                    {
                        MQHelper.MQSendMsg(webResponse.Data.ToString(), MQqueue.Equ_SendTask_2.ToString());
                    }
                    else if (equmlcnc.EquipmentNo == "3" && EQU_COM_DEFINITION_TASKml.Command != "TASK001")
                    {
                        MQHelper.MQSendMsg(webResponse.Data.ToString(), MQqueue.Equ_SendTask_3.ToString());
                    }
                    else if (equmlcnc.EquipmentNo == "3" && EQU_COM_DEFINITION_TASKml.Command != "TASK001")
                    {
                        MQHelper.MQSendMsg(webResponse.Data.ToString(), MQqueue.Equ_SendTask_4.ToString());
                    }
                    else
                    {
                        MQHelper.MQSendMsg(webResponse.Data.ToString(), MQqueue.Equ_SendTask.ToString());
                    }

                }
                else
                {
                    if (equmlcnc.EquipmentNo == "1")
                    {
                        MQHelper.MQSendMsg(webResponse.Data.ToString(), MQqueue.Equ_SendTask_1.ToString());
                    }
                    else if (equmlcnc.EquipmentNo == "2")
                    {
                        MQHelper.MQSendMsg(webResponse.Data.ToString(), MQqueue.Equ_SendTask_2.ToString());
                    }
                    else if (equmlcnc.EquipmentNo == "3")
                    {
                        MQHelper.MQSendMsg(webResponse.Data.ToString(), MQqueue.Equ_SendTask_3.ToString());
                    }
                    else if (equmlcnc.EquipmentNo == "4")
                    {
                        MQHelper.MQSendMsg(webResponse.Data.ToString(), MQqueue.Equ_SendTask_4.ToString());
                    }
                    else
                    {
                        MQHelper.MQSendMsg(webResponse.Data.ToString(), MQqueue.Equ_SendTask.ToString());
                    }
                }



            }
        }
        /// <summary>
        /// 调度任务
        /// </summary>
        /// <param name="EQU_COM_DEFINITION_TASKml"></param>
        /// <param name="item"></param>
        /// <param name="equ_tool"></param>
        /// <param name="iNTE_SHELVES"></param>
        private static void EquComDefinitionTask(EQU_COM_DEFINITION_TASK EQU_COM_DEFINITION_TASKml, EQU_EQUIPMENT actionEquipment,
            EQU_TOOL equ_tool, List<INTE_SHELVES> iNTE_SHELVES, string status, EQU_EQUIPMENT cncEquEquipment)
        {
            var dt = DateTime.Now;
            EQU_COM_DEFINITION_TASKml.ActionEquipmentId = actionEquipment.Id.ToString().ToUpper();
            EQU_COM_DEFINITION_TASKml.Status = status;//// ((int)StatusAction.Executing).ToString();// "2";//执行中
            EQU_COM_DEFINITION_TASKml.ExecuteStart = dt;
            EQU_COM_DEFINITION_TASKml.IsCurrentOrderCode = "1";

            if (equ_tool != null)
            {
                equ_tool.process_start_time = dt;
                var inteShelves = iNTE_SHELVES.Where(t => t.DBCode == equ_tool.location).FirstOrDefault();
                EQU_COM_DEFINITION_TASKml.SHELVES_Id = inteShelves != null ? inteShelves.INTE_SHELVES_Id.ToString().ToUpper() : null;
            }
            if (EQU_COM_DEFINITION_TASKml.Command == "TW0031")//换刀
            {
                var inteShelves = iNTE_SHELVES.Where(t => t.DBCode == cncEquEquipment.Location).FirstOrDefault();
                EQU_COM_DEFINITION_TASKml.SHELVES_Id = inteShelves != null ? inteShelves.INTE_SHELVES_Id.ToString().ToUpper() : null;
            }
        }

        /// <summary>
        /// 生产执行
        /// </summary>
        /// <param name="manuExecution"></param>
        /// <param name="piece"></param>
        /// <param name="orderid"></param>
        /// <param name="eQU_COM_DEFINITION_TASK"></param>
        private void ManuExecution(ref MANU_EXECUTION manuExecution, PROC_MATERIAL piece, string orderid,
            EQU_COM_DEFINITION_TASK eQU_COM_DEFINITION_TASK, EQU_COM_DEFINITION_TASK lastEquComDefinitionTask, PLAN_WORK_ORDER plan_work_order)
        {
            if (manuExecution == null)
            {
                manuExecution = new MANU_EXECUTION();
                manuExecution.Qty = 1;
                manuExecution.SFC = piece.workpiece_name;
                manuExecution.Order_Id = orderid.ToString().ToUpper();
                manuExecution.Equipment_Id = eQU_COM_DEFINITION_TASK.Equipment_Id;
                manuExecution.OperationId = eQU_COM_DEFINITION_TASK.OperationName;
                manuExecution.LastOperationId = lastEquComDefinitionTask != null ? lastEquComDefinitionTask.OperationName : null;
                manuExecution.Status = plan_work_order.Status;
                repository.DbContext.Entry(manuExecution).State = EntityState.Added;


            }
            else
            {
                manuExecution.Qty = 1;
                manuExecution.SFC = piece.workpiece_name;
                manuExecution.Order_Id = orderid.ToString().ToUpper();
                manuExecution.Equipment_Id = eQU_COM_DEFINITION_TASK.Equipment_Id;
                manuExecution.OperationId = eQU_COM_DEFINITION_TASK.OperationName;
                manuExecution.LastOperationId = lastEquComDefinitionTask != null ? lastEquComDefinitionTask.OperationName : null;
                manuExecution.Status = plan_work_order.Status;
                repository.DbContext.Entry(manuExecution).State = EntityState.Modified;
            }
            repository.SaveChanges();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="manuExecution"></param>
        /// <param name="plan_work_order"></param>
        private void ManuExecutionState(ref MANU_EXECUTION manuExecution, PLAN_WORK_ORDER plan_work_order)
        {
            if (manuExecution == null)
            {



            }
            else
            {

                manuExecution.Status = plan_work_order.Status;
                repository.DbContext.Entry(manuExecution).State = EntityState.Modified;
            }
            repository.SaveChanges();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="plan_work_order"></param>
        /// <param name="eQU_COM_DEFINITION_TASK"></param>
        private void PlanWorkOrder(ref PLAN_WORK_ORDER plan_work_order, EQU_COM_DEFINITION_TASK eQU_COM_DEFINITION_TASK)
        {
            plan_work_order.Status = ((int)StatusOrder.Produce).ToString();
            plan_work_order.process_Status = (int)StatusProcess.Produce;
            if (eQU_COM_DEFINITION_TASK.Command == "TW001")
            {
                //plan_work_order.process_Status = (int)StatusProcess.Produce;
                //plan_work_order.Status = ((int)StatusOrder.Produce).ToString();
            }

            if (eQU_COM_DEFINITION_TASK.Command == "TW003")//上料
            {
                plan_work_order.ExecuteStart = DateTime.Now;
            }
            if (eQU_COM_DEFINITION_TASK.Command == "TW005")//
            {
                var order = plan_work_order.OrderCode;
                var sumTime = repository.Find<EQU_COM_DEFINITION_TASK>(t => t.OrderCode == order && t.ExecuteTaskDiffTime != null && (t.Command == "TW004" || t.Command == "TW0041")).Sum(t => t.ExecuteTaskDiffTime);
                plan_work_order.ProcessingTime = sumTime;
            }
            if (eQU_COM_DEFINITION_TASK.Command == "TW006")
            {
                plan_work_order.Status = ((int)StatusOrder.Completed).ToString();
                plan_work_order.process_Status = (int)StatusProcess.Completed;
                plan_work_order.ExecuteEnd = DateTime.Now;

            }
            repository.DbContext.Entry(plan_work_order).State = EntityState.Modified;
            repository.SaveChanges();
        }
        /// <summary>
        /// 生产汇总
        /// </summary>
        /// <param name="manuSummary"></param>
        /// <param name="piece"></param>
        /// <param name="orderid"></param>
        /// <param name="eQU_COM_DEFINITION_TASK"></param>
        private void ManuSummary(ref MANU_SUMMARY manuSummary, PROC_MATERIAL piece, string orderid,
            EQU_COM_DEFINITION_TASK eQU_COM_DEFINITION_TASK)
        {
            if (manuSummary == null)
            {
                manuSummary = new MANU_SUMMARY();
                manuSummary.OperationId = eQU_COM_DEFINITION_TASK.OperationName;
                manuSummary.WorkOrderId = orderid.ToString().ToUpper();
                manuSummary.EquipmentId = eQU_COM_DEFINITION_TASK.Equipment_Id;
                manuSummary.SFC = piece.workpiece_name;
                manuSummary.BeginTime = eQU_COM_DEFINITION_TASK.ExecuteStart;
                manuSummary.EndTime = eQU_COM_DEFINITION_TASK.ExecuteEnd;

                repository.DbContext.Entry(manuSummary).State = EntityState.Added;
            }
            else
            {
                manuSummary.OperationId = eQU_COM_DEFINITION_TASK.OperationName;
                manuSummary.WorkOrderId = orderid.ToString().ToUpper();
                manuSummary.EquipmentId = eQU_COM_DEFINITION_TASK.Equipment_Id;
                manuSummary.SFC = piece.workpiece_name;
                manuSummary.BeginTime = eQU_COM_DEFINITION_TASK.ExecuteStart;
                manuSummary.EndTime = eQU_COM_DEFINITION_TASK.ExecuteEnd;
                repository.DbContext.Entry(manuSummary).State = EntityState.Modified;
            }
            repository.SaveChanges();
        }

        /// <summary>
        /// 返回Equ_TASKVM
        /// </summary>
        /// <param name="equ_task"></param>
        /// <param name="equml"></param>
        /// <param name="eQU_COM_DEFINITION_TASK"></param>
        /// <param name="plan_work_order"></param>
        /// <param name="equ_tool"></param>
        /// <param name="pROC_PROGRAM"></param>
        /// <param name="pROC_PROGRAMs"></param>
        /// <returns></returns>
        private Equ_TASKVM EquTaskvm1(EQU_TASK equ_task, EQU_EQUIPMENT equml, EQU_COM_DEFINITION_TASK eQU_COM_DEFINITION_TASK,
            PLAN_WORK_ORDER plan_work_order, EQU_TOOL equ_tool, PROC_PROGRAM pROC_PROGRAM, List<PROC_PROGRAM> pROC_PROGRAMs, PROC_MATERIAL piece)
        {
            Equ_TASKVM equ_TASKVM1 = new Equ_TASKVM();
            equ_TASKVM1.Status = equ_task.Status;// 1;
            equ_TASKVM1.EquipmentCode = equml.EquipmentCode;//设备编号
            equ_TASKVM1.SubPathNo = eQU_COM_DEFINITION_TASK.SubPathNo.ToInt();
            equ_TASKVM1.Command = equ_task.TaskCode;// eQU_COM_DEFINITION_TASK.Command;

            equ_TASKVM1.StartTime = DateTime.Now;
            equ_TASKVM1.Unit = equml.unit == null ? 1 : equml.unit.Value;
            equ_TASKVM1.WorkOrderCode = SplitEx(plan_work_order.OrderCode, 2);//调度id
            equ_TASKVM1.OrderCode = plan_work_order.OrderCode;
            equ_TASKVM1.TaskNo = eQU_COM_DEFINITION_TASK.TaskNo;//调度id
            equ_TASKVM1.DbCode = equ_task.DbCode;
            equ_TASKVM1.toolId = equ_tool != null ? equ_tool.Id.ToString() : "";
            equ_TASKVM1.ProgramName = pROC_PROGRAM != null ? pROC_PROGRAM.program_name : "";
            CurrentTool currentTool = new CurrentTool();
            SetCurrenToll(equ_tool, currentTool, equ_task, equ_TASKVM1, pROC_PROGRAMs, equml);

            equ_TASKVM1.CurrentTool = currentTool;
            #region by 2024.10.24
            EQU_EQUIPMENT machine = repository.Find<EQU_EQUIPMENT>(t => t.Description == plan_work_order.processing_machines).FirstOrDefault();
            UpperMachine machinenew = new UpperMachine();
            // machinenew.Id = machine.id;
            machinenew.Name = machine.name;
            machinenew.LatheSpec = machine.latheSpec;
            machinenew.MachineType = machine.machine_type;
            machinenew.ProcessType = machine.process_type;
            machinenew.G54Supplement = (double)machine.g54_supplement;
            machinenew.ToolHeight = machine.tool_height != null ? (double)machine.tool_height : 0;
            machinenew.ProcessPrecision = machine.process_precision;
            machinenew.ItineraryX = machine.itinerary_x != null ? (double)machine.itinerary_x : 0;
            machinenew.ItineraryY = machine.itinerary_y != null ? (double)machine.itinerary_y : 0;
            machinenew.ItineraryZ = machine.itinerary_z != null ? (double)machine.itinerary_z : 0;
            machinenew.BasicX = machine.basic_x != null ? (double)machine.basic_x : 0;
            machinenew.BasicY = machine.basic_y != null ? (double)machine.basic_y : 0;
            machinenew.BasicZ = machine.basic_z != null ? (double)machine.basic_z : 0;
            machinenew.ChangeToolX = machine.change_tool_x != null ? (double)machine.change_tool_x : 0;
            machinenew.ChangeToolY = machine.change_tool_y != null ? (double)machine.change_tool_y : 0;
            machinenew.ChangeToolZ = machine.change_tool_z != null ? (double)machine.change_tool_z : 0;
            machinenew.FeedX = machine.feed_x != null ? (double)machine.feed_x : 0;
            machinenew.FeedY = machine.feed_y != null ? (double)machine.feed_y : 0;
            machinenew.FeedZ = machine.feed_z != null ? (double)machine.feed_z : 0;
            machinenew.Unit = machine.unit;
            machinenew.Host = machine.host;
            machinenew.Port = machine.port;
            machinenew.NcType = machine.nc_type;
            machinenew.NcCardNo = machine.nc_card_no;
            machinenew.UseStatus = machine.use_status.Value;

            var workOrderVM = new UpperWorkOrder();//_mapper.Map<upper_work_orderVM>(uwo);
            workOrderVM.WorkOrderId = plan_work_order.workpiece_id;// uwo.work_order_id;

            workOrderVM.WorkOrderNumber = plan_work_order.work_order_number;// uwo.work_order_number;
            workOrderVM.WorkpieceId = plan_work_order.workpiece_id;// uwo.workpiece_id;
            workOrderVM.Priority = plan_work_order.priority.Value;// uwo.priority;
            workOrderVM.MaterialId = plan_work_order.material_id;// uwo.material_id;
            workOrderVM.ProcessingGrade = plan_work_order.processing_grade.Value;// uwo.processing_grade;
            workOrderVM.Length = plan_work_order.length != null ? (double)plan_work_order.length : 0;// uwo.length != null ? (double)uwo.length : 0;
            workOrderVM.Width = plan_work_order.width != null ? (double)plan_work_order.width : 0;// uwo.width != null ? (double)uwo.width : 0;
            workOrderVM.Height = plan_work_order.height != null ? (double)plan_work_order.height : 0;// uwo.height != null ? (double)uwo.height : 0;
            workOrderVM.MeasureNumber = plan_work_order.measure_number;// uwo.measure_number;
            workOrderVM.CentringNumber = plan_work_order.centring_number;// uwo.centring_number;
            workOrderVM.MakeLevelNumber = plan_work_order.make_level_number;// uwo.make_level_number;
            workOrderVM.Accuracy = plan_work_order.accuracy != null ? (double)plan_work_order.accuracy : 0;// uwo.accuracy != null ? (double)uwo.accuracy : 0;
            workOrderVM.ProcessStatus = (uint)plan_work_order.process_Status;//(uint)uwo.process_Status;
            //workOrderVM.CreatTime = uwo.work_order_id;
            //workOrderVM.UpdateTime = uwo.work_order_id;
            //workOrderVM.IsDeleted = uwo.work_order_id;
            //  workOrderVM.Workpiece = piece;
            var workPiece = new UpperWorkpiece();
            workPiece.WorkpieceWidth = piece.workpiece_width != null ? (double)piece.workpiece_width : 0;
            workPiece.XInstance = piece.x_instance != null ? (double)piece.x_instance : 0;
            workPiece.YInstance = piece.y_instance != null ? (double)piece.y_instance : 0;
            workPiece.ZInstance = piece.z_instance != null ? (double)piece.z_instance : 0;
            workOrderVM.Workpiece = workPiece;
            CncInfo cncInfo = new CncInfo()
            {
                Machine = machinenew,
                WorkOrder = workOrderVM
            };
            #endregion
            equ_TASKVM1.CncInfo = cncInfo;
            return equ_TASKVM1;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> OrderActivation(Equ_TASKVM equ_TASKVM)
        {
            string msg = string.Empty;
            try
            {
                var id = equ_TASKVM.TaskNo.ToGuid();
                var eQU_COM_DEFINITION_TASK = await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(t => t.ComDefintion_TaskId == id);
                eQU_COM_DEFINITION_TASK.Status = equ_TASKVM.Status;
                repository.Update<EQU_COM_DEFINITION_TASK>(eQU_COM_DEFINITION_TASK);

                repository.SaveChanges();
                Logger.Info(LoggerType.Success, equ_TASKVM.Serialize(), webResponse.Message, msg);
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                {
                    throw new Exception(ex.Message + ex.StackTrace);
                }
                Logger.Info(LoggerType.Exception, equ_TASKVM.Serialize(), webResponse.Message, msg);
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {

                Logger.Info(LoggerType.Login, equ_TASKVM.Serialize(), webResponse.Message, msg);
            }
        }
        #endregion


        //       
        //}
        #region  by guoyuguo 2024.9.11 刀具管理
        public async Task<ApiResponse> GetAllAsync([FromQuery] ToDoParameter param, IMapper _mapper)
        {
            Expression<Func<V_EQU_TOOL_ORDER, bool>> orFilter = x => true;
            if (param.Status != null)
            {
                orFilter = orFilter.And(x => x.use_status == param.Status);
            }
            if (param.Search != null)
            {
                orFilter = orFilter.And(x => x.EquipmentCode.Contains(param.Search) || x.OrderCode.Contains(param.Search) || x.Identifier.Contains(param.Search) || x.Holder_Code.Contains(param.Search) || x.tool_name.StartsWith(param.Search));
            }

            var query = await repository.DbContext.Set<V_EQU_TOOL_ORDER>().Where(orFilter).ToListAsync();

            var apirs = new ApiResponse("", true);
            var toDoDtos = _mapper.Map<List<ToDoDto>>(query);
            foreach (var item in toDoDtos)
            {
                item.Status = item.use_status == null ? 0 : item.use_status.Value;
            }
            apirs.Result = new PagedList<ToDoDto>(toDoDtos, param.PageIndex, param.PageSize, 0);
            return apirs;
        }
        public async Task<ApiResponse> GetINTE_SHELVES([FromQuery] ToDoParameter param, IMapper _mapper)
        {
            Expression<Func<INTE_SHELVES, bool>> orFilter = x => true;
            if (param.Search != null)
            {
                orFilter = orFilter.And(x => x.LocationCode.Contains(param.Search));
            }
            var query = await repository.DbContext.Set<INTE_SHELVES>().Where(orFilter).ToListAsync();

            var apirs = new ApiResponse("", true);
            var toDoDtos = _mapper.Map<List<INTE_SHELVES_Dto>>(query);

            apirs.Result = new PagedList<INTE_SHELVES_Dto>(toDoDtos, param.PageIndex, param.PageSize, 0);
            return apirs;
        }
        public async Task<ApiResponse> FirstTool([FromQuery] ToDoParameter param, IMapper _mapper)
        {
            Expression<Func<V_EQU_TOOL_ORDER, bool>> orFilter = x => true;

            if (param.Status != null)
            {
                orFilter = orFilter.And(x => x.use_status == param.Status);
            }
            if (param.Search != null)
            {
                orFilter = orFilter.And(x => x.RfidCode.Contains(param.Search));
            }
            var query = await repository.DbContext.Set<V_EQU_TOOL_ORDER>().Where(orFilter).FirstAsync();

            var querynew = _mapper.Map<V_EQU_TOOL_ORDERTDD>(query);
            querynew.EQU_TASKTDDS = await repository.DbContext.Set<EQU_TASK>().Where(t => t.TaskGroup == "TG004").ToListAsync();
            return new ApiResponse(true, querynew);

        }
        public async Task<ApiResponse> FirstToolEqu(string rfidCode, IMapper _mapper)
        {

            Expression<Func<EQU_TOOL, bool>> orFilter = x => true;

            if (!string.IsNullOrEmpty(rfidCode))
            {
                orFilter = orFilter.And(x => x.RfidCode == rfidCode);
            }
            else
            {
                return new ApiResponse("rfidCode不能为空!", false);
            }

            var query = await repository.DbContext.Set<EQU_TOOL>().Where(orFilter).FirstOrDefaultAsync();
            if (query == null)
            {

                return new ApiResponse(false, "未找到该数据");
            }
            //var querynew = _mapper.Map<V_EQU_TOOL_ORDERTDD>(query);
            //querynew.EQU_TASKTDDS = await repository.DbContext.Set<EQU_TASK>().Where(t => t.TaskGroup == "TG004").ToListAsync();
            return new ApiResponse(true, query);

        }
        /// <summary>
        /// 正负判断
        /// </summary>
        /// <param name="inputnum"></param>
        /// <param name="inputnumtype"></param>
        /// <returns></returns>
        private double GetNum(double inputnum, double inputnumtype)
        {
            if (inputnumtype <= 0)
            {

            }
            else
            {
                inputnum = -1 * inputnum;
            }
            return inputnum;
        }
        public async Task<ApiResponse> FirstToolEquNew(string rfidCode, IMapper _mapper)
        {
            Expression<Func<EQU_TOOL, bool>> orFilter = x => true;

            //if (!string.IsNullOrEmpty(rfidCode))
            //{
            //    orFilter = orFilter.And(x => x.RfidCode == rfidCode);
            //}
            //else
            //{
            //    return new ApiResponse("rfidCode不能为空!", false);
            //}
            var query = await repository.DbContext.Set<EQU_TOOL>().Where(orFilter).FirstOrDefaultAsync();
            //if (query == null)
            //{
            //    return new ApiResponse(false, "未找到该数据");
            //}
            CurrentToolPLC currentToolPlc = new CurrentToolPLC();
            string ip = "192.168.1.190";

            var isConnect = IsIpConnect(ip);
            if (!isConnect)
            {
                return new ApiResponse(false, $"{ip}连接不上！");
            }
            var isOpen = PlcHelper.Instance.OpenPlc(CpuType.S71500, 0, 1, ip);
            if (isOpen)   //判断是否成功
            {
                var v1 = (double)PlcHelper.Instance.ReadReal(6, 0);//R角度
                var v2 = (double)PlcHelper.Instance.ReadReal(6, 4);//直径
                var v3 = (double)PlcHelper.Instance.ReadReal(6, 8);//刀长到中心线误差


                var v6 = (double)PlcHelper.Instance.ReadReal(6, 20);//总长正负（刀长到中心线误差）
                var v7 = (double)PlcHelper.Instance.ReadReal(6, 24);//刀柄正负（刀柄直径到中心线误差）

                var v4 = GetNum((double)PlcHelper.Instance.ReadReal(6, 8), v6);//刀柄直径到中心线误差
                var v5 = GetNum((double)PlcHelper.Instance.ReadReal(6, 12), v7);//刀柄半径 [-0.5, 0.5]

                var Ace1DTheory28 = (double)PlcHelper.Instance.ReadReal(6, 28);//加长杆长度
                if (Ace1DTheory28 == 2147483648)
                {
                    Console.Write("NG");
                }
                else
                {
                    currentToolPlc.Ace1DTheory = (decimal)Ace1DTheory28;

                }
                if (v1 == 2147483648)
                {
                    Console.Write("NG");
                }
                else
                {
                    currentToolPlc.RealityR = (decimal)v1;

                }
                if (v2 == 2147483648)
                {
                    Console.Write("NG");
                }
                else
                {// [0 , 0.02] 
                    currentToolPlc.HolderBD = (decimal)v2;
                    if ((query.HolderBDTheory - (decimal)0) <= (decimal)v2 && (decimal)v2 <= (query.HolderBDTheory + (decimal)3))
                    {
                        currentToolPlc.IsHolderBD = true;
                    }
                    else
                    {
                        currentToolPlc.IsHolderBD = false;
                    }
                }
                if (v3 == 2147483648)
                {
                    Console.Write("NG");
                }
                else
                {
                    //[0,3] 
                    currentToolPlc.RealityPairingLength = (decimal)v3;
                    if ((query.pairing_length - (decimal)0) <= (decimal)v3 && (decimal)v3 <= (query.pairing_length + (decimal)3))
                    {
                        currentToolPlc.IsRealityPairingLength = true;
                    }
                    else
                    {
                        currentToolPlc.IsRealityPairingLength = false;
                    }
                }
                if (v4 == 2147483648)
                {
                    Console.Write("NG");
                }
                else
                {
                    //[-3,0.5] 
                    currentToolPlc.RealityKnifeWidth = ((decimal)v4 + query.knife_length.Value);
                    if ((query.knife_length - (decimal)3) <= ((decimal)v4 + query.knife_length) && ((decimal)v4 + query.knife_length) <= (query.knife_length + (decimal)0.5))
                    {
                        currentToolPlc.IsHolderL = true;
                    }
                    else
                    {
                        currentToolPlc.IsHolderL = false;
                    }
                }
                if (v5 == 2147483648)
                {
                    Console.Write("NG");
                }
                else
                {
                    if ((query.HolderBDTheory - (query.HolderBDTheory + (decimal)0.5)) <= (decimal)v5 && (decimal)v5 <= (query.HolderBDTheory + (query.HolderBDTheory + (decimal)0.5)))
                    {
                        currentToolPlc.IsHolderBD = true;
                    }
                    else
                    {
                        currentToolPlc.IsHolderBD = false;
                    }
                    currentToolPlc.HolderSD = (decimal)v5;

                }
            }
            PlcHelper.Instance.ClosePlc(PlcHelper.Instance.Plc);
            currentToolPlc.Msg = $"刀柄半径[-0.5, 0.5]:{currentToolPlc.IsHolderBD}";
            return new ApiResponse(true, currentToolPlc);

        }
        /// <summary>
        /// ip 连接判断
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public bool IsIpConnect(string ip)
        {

            // ip = "192.168.1.190"; // 替换为你想要ping的IP地址
            Ping pingSender = new Ping();
            var isConnect = false;
            try
            {
                PingReply reply = pingSender.Send(ip, 120);
                if (reply.Status == IPStatus.Success)
                {
                    isConnect = true;
                }
                else
                {
                    isConnect = false;
                }
            }
            catch (PingException e)
            {
                Console.WriteLine(e.ToString());
            }

            return isConnect;
        }

        public async Task<ApiResponse> UpdateToolEquByRfid([FromBody] EQU_TOOL_Dto model, IMapper _mapper)
        {
            Expression<Func<EQU_TOOL, bool>> orFilter = x => true;

            if (!string.IsNullOrEmpty(model.RfidCode))
            {
                orFilter = orFilter.And(x => x.RfidCode == model.RfidCode);
            }
            else
            {
                return new ApiResponse("rfidCode不能为空!", false);
            }
            var firstquery = await repository.FindAsyncFirst<EQU_TOOL>(t => t.RfidCode == model.RfidCode);
            if (firstquery == null)
            {
                return new ApiResponse(false, "未找到该数据");
            }
            //firstquery = _mapper.Map<EQU_TOOL>(model);
            firstquery.Ace1D = model.Ace1D;
            firstquery.Ace1L = model.Ace1L;
            firstquery.Ace2D = model.Ace2D;
            firstquery.Ace2L = model.Ace2L;
            firstquery.Ace3D = model.Ace3D;
            firstquery.Ace3L = model.Ace3L;
            firstquery.blade_length = model.blade_length;
            firstquery.reality_R = model.reality_R;
            firstquery.reality_blade_length = model.reality_blade_length;
            firstquery.reality_knife_length = model.reality_knife_length;
            firstquery.reality_pairing_length = model.reality_pairing_length;


            repository.Update<EQU_TOOL>(firstquery);
            await repository.SaveChangesAsync();
            return new ApiResponse(true, firstquery);
        }
        public async Task<ApiResponse> GetAsync(string Id)
        {
            Guid guid = Guid.Parse(Id);
            var firstquery = await repository.FindAsyncFirst<V_EQU_TOOL_ORDER>(t => t.Id == guid);
            if (firstquery == null)
            {
                return new ApiResponse(false, "未找到该数据");
            }
            return new ApiResponse(true, firstquery);
        }
        public async Task<ApiResponse> UpdateAsync([FromBody] ToDoDto model, IMapper _mapper)
        {
            //Guid guid = Guid.Parse(model.Id);
            var firstquery = await repository.FindAsyncFirst<EQU_TOOL>(t => t.Id == model.Id);
            firstquery = _mapper.Map<EQU_TOOL>(model);
            repository.Update<EQU_TOOL>(firstquery);
            repository.SaveChanges();
            return new ApiResponse(true, firstquery);
        }
        public async Task<ApiResponse> AddAsync([FromBody] ToDoDto model, IMapper _mapper)
        {
            var mladd = _mapper.Map<EQU_TOOL>(model);
            mladd.Id = Guid.NewGuid();
            var query = await repository.DbContext.AddAsync<EQU_TOOL>(mladd);

            repository.SaveChanges();

            return new ApiResponse(true, query);
        }
        public async Task<ApiResponse> DeleteAsync(string id)
        {
            Guid guid = Guid.Parse(id);
            var firstquery = await repository.FindAsyncFirst<EQU_TOOL>(t => t.Id == guid);
            if (firstquery == null)
            {
                return new ApiResponse(false, "未找到该数据");
            }
            repository.DbContext.Remove<EQU_TOOL>(firstquery);
            repository.SaveChanges();
            return new ApiResponse(true, firstquery);
        }
        public async Task<ApiResponse> Summary(IMapper _mapper)
        {
            try
            {
                // var todosli = repository.Find<EQU_TOOL>(t => t.use_status == 0);
                var todosli = await repository.DbContext.Set<V_EQU_TOOL_ORDER>().Where(t => t.use_status == 0 || t.use_status == null).ToListAsync();
                var todos = _mapper.Map<List<ToDoDto>>(todosli);
                List<int> lis = new List<int>();
                lis.Add(0);
                lis.Add(1);
                SummaryDto summary = new SummaryDto();
                summary.Sum = repository.Find<V_EQU_TOOL_ORDER>(t => lis.Contains(t.use_status.Value)).Count();// todos.Count(); //汇总待办事项数量
                summary.CompletedCount = repository.Find<V_EQU_TOOL_ORDER>(t => t.use_status == 1).Count();// todos.Where(t => t.Status == 1).Count(); //统计完成数量
                summary.CompletedRatio = (summary.CompletedCount / (double)summary.Sum).ToString("0%"); //统计完成率
                summary.MemoeCount = todos.Count();  //未完成数量
                                                     //   summary.MemoeCount = memos.Count();  //汇总备忘录数量
                summary.ToDoList = new ObservableCollection<ToDoDto>(todos);
                // summary.MemoList = new ObservableCollection<MemoDto>(Mapper.Map<List<MemoDto>>(memos));

                return new ApiResponse(true, summary);
            }
            catch (Exception ex)
            {
                return new ApiResponse(false, "");
            }
        }
        #endregion
        #region by guoyuguo 2024.9.13 任务管理
        public async Task<ApiResponse> GetAllTaskAsync([FromQuery] ToDoParameter param, IMapper _mapper)
        {
            Expression<Func<V_Equ_Task_Command, bool>> orFilter = x => true;
            //if (param.Status != null)
            //{
            //    orFilter = orFilter.And(x => x.use_status == param.Status);
            //}
            //if (param.Search != null)
            //{
            //    orFilter = orFilter.And(x => x.Identifier.Contains(param.Search) || x.Holder_Code.Contains(param.Search) || x.tool_name.StartsWith(param.Search));
            //}
            var TaskItems = await repository.DbContext.Set<EQU_COM_DEFINITION_TASK>().ToListAsync();
            var query = await repository.DbContext.Set<V_Equ_Task_Command>().Where(orFilter).ToListAsync();

            var apirs = new ApiResponse("", true);
            //var toDoDtos = _mapper.Map<List<ToDoDto>>(query);
            var toDoDtos = query.Select(x => new ToDoDto
            {
                Id = x.Id,
                Command = x.Command,
                EquipmentNameZH = x.EquipmentNameZH,
                EquipmentCode = x.EquipmentCode,
                TaskItems = TaskItems.ToList()
            }).ToList();

            apirs.Result = new PagedList<ToDoDto>(toDoDtos, param.PageIndex, param.PageSize, 0);
            return apirs;
        }
        #endregion
        #region by guoyuguo 2024.10.12 PLC数据
        public async Task<WebResponseContent> GetPLCData(IMapper _mapper)
        {
            string msg = string.Empty;
            try
            {
                List<PLCData> pLCDatas = new List<PLCData>();
                Expression<Func<EQU_PLCConfig, bool>> orFilter = x => true;
                Expression<Func<EQU_EQUIPMENT, bool>> orFilterequ = x => true;
                var id = Guid.Parse("0D3DABDE-775F-EF11-837F-581122BC3390");

                var query1 = await repository.DbContext.Set<EQU_PLCConfig>().Where(orFilter).FirstAsync();
                //  var query = await repository.FindAsync<EQU_PLCConfig>(orFilter);
                //  var querynew = _mapper.Map<V_EQU_TOOL_ORDERTDD>(query);
                var queryEqu = await repository.DbContext.Set<EQU_EQUIPMENT>().Where(t => t.Id == id).ToListAsync();

                // var query = await repository.FindAsync<EQU_PLCConfig>(orFilter);


                //      var queryEqu =await _repository.FindAsync<EQU_EQUIPMENT>(orFilterequ);
                //await repository.DbContext.Set<EQU_EQUIPMENT>().Where(t=>t.EquipmentCode== "JCR_001").ToListAsync();
                // foreach (var item in query)
                //{
                //    PLCData pLCData= new PLCData();
                //    pLCData.EquipmentId = item.EquipmentId;
                //    //queryEqu.ForEach(t =>
                //    //{
                //    //    pLCData.EquipmentCode = t.EquipmentCode;
                //    //    pLCData.EquipmentName = t.EquipmentNameZH;
                //    //});
                //    pLCDatas.Add(pLCData);
                //}
                Logger.Info(LoggerType.Success, pLCDatas.Serialize(), webResponse.Message, msg);
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                {
                    throw new Exception(ex.Message + ex.StackTrace);
                }
                Logger.Info(LoggerType.Exception, "", webResponse.Message, msg);
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {

                Logger.Info(LoggerType.Login, "", webResponse.Message, msg);
            }
        }
        #endregion
        /// <summary>
        /// TD300 启动start
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>

        public async Task<WebResponseContent> Start([FromBody] MANU_EXECUTION taskOptions)
        {


            var equComDefinitionTask = await GetEquComDefinitionTask(taskOptions, "TD300");

            Equ_TASKVM equ_TASKVM1 = new Equ_TASKVM();
            equ_TASKVM1.Command = equComDefinitionTask.Command;
            equ_TASKVM1.TaskNo = equComDefinitionTask.TaskNo;//调度id
            webResponse.Data = equ_TASKVM1.Serialize().ToString();
            //webResponse.ExData = "[" + equ_TASKVM1.Serialize().ToString() + "]";
            WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
            {
                repository.DbContext.Set<MANU_EXECUTION>().Update(taskOptions);
                repository.DbContext.Set<EQU_COM_DEFINITION_TASK>().Add(equComDefinitionTask);

                repository.SaveChanges();
                return webResponse.OK(ResponseType.Success);
            });
            //判断事务是否执行成功
            if (!webResponse1.Status)
            {
                return new WebResponseContent().Error("返回消息");
            }


            return webResponse.OK(ResponseType.Success);
        }


        /// <summary>
        /// TD200 暂停pause
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> Pause([FromBody] MANU_EXECUTION taskOptions)
        {
            var equComDefinitionTask = await GetEquComDefinitionTask(taskOptions, "TD200");
            Equ_TASKVM equ_TASKVM1 = new Equ_TASKVM();
            equ_TASKVM1.Command = equComDefinitionTask.Command;// eQU_COM_DEFINITION_TASK.Command;
            equ_TASKVM1.TaskNo = equComDefinitionTask.TaskNo;//调度id
            webResponse.Data = equ_TASKVM1.Serialize().ToString();
            //webResponse.ExData = "[" + equ_TASKVM1.Serialize().ToString() + "]";
            WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
            {
                repository.DbContext.Set<EQU_COM_DEFINITION_TASK>().Add(equComDefinitionTask);
                repository.SaveChanges();
                return webResponse.OK(ResponseType.Success);
            });
            //判断事务是否执行成功
            if (!webResponse1.Status)
            {
                return new WebResponseContent().Error("返回消息");
            }


            return webResponse.OK(ResponseType.Success);
        }
        /// <summary>
        /// TD100 紧急暂停stop
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> Stop([FromBody] MANU_EXECUTION taskOptions)
        {
            var equComDefinitionTask = await GetEquComDefinitionTask(taskOptions, "TD100");
            Equ_TASKVM equ_TASKVM1 = new Equ_TASKVM();
            equ_TASKVM1.Command = equComDefinitionTask.Command;// eQU_COM_DEFINITION_TASK.Command;
            equ_TASKVM1.TaskNo = equComDefinitionTask.TaskNo;//调度id
            webResponse.Data = equ_TASKVM1.Serialize().ToString();
            WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
            {
                repository.DbContext.Set<EQU_COM_DEFINITION_TASK>().Add(equComDefinitionTask);
                repository.SaveChanges();
                return webResponse.OK(ResponseType.Success);
            });
            //判断事务是否执行成功
            if (!webResponse1.Status)
            {
                return new WebResponseContent().Error("返回消息");
            }


            return webResponse.OK(ResponseType.Success);
        }
        /// <summary>
        /// TD400  终止termination
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> Termination([FromBody] MANU_EXECUTION taskOptions)
        {
            var equComDefinitionTask = await GetEquComDefinitionTask(taskOptions, "TD400");
            Equ_TASKVM equ_TASKVM1 = new Equ_TASKVM();
            equ_TASKVM1.Command = equComDefinitionTask.Command;// eQU_COM_DEFINITION_TASK.Command;
            equ_TASKVM1.TaskNo = equComDefinitionTask.TaskNo;//调度id
            webResponse.Data = equ_TASKVM1.Serialize().ToString();
            //webResponse.ExData = "[" + equ_TASKVM1.Serialize().ToString() + "]";
            WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
            {
                repository.DbContext.Set<EQU_COM_DEFINITION_TASK>().Add(equComDefinitionTask);
                repository.SaveChanges();
                // repository.Update<EQU_COM_DEFINITION_TASK>(EQU_COM_DEFINITION_TASKml, true);
                return webResponse.OK(ResponseType.Success);
            });
            //判断事务是否执行成功
            if (!webResponse1.Status)
            {
                return new WebResponseContent().Error("返回消息");
            }


            return webResponse.OK(ResponseType.Success);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        private async Task<EQU_COM_DEFINITION_TASK> GetEquComDefinitionTask(MANU_EXECUTION taskOptions, string taskCode)
        {
            EQU_TASK equTask = await repository.FindAsyncFirst<EQU_TASK>(t => t.TaskCode == taskCode);
            var orderId = Guid.Parse(taskOptions.Order_Id);
            PLAN_WORK_ORDER planWorkOrder = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.Order_Id == orderId);
            if (planWorkOrder != null)
            {
                taskOptions.Status = planWorkOrder.Status;
            }
            int count = repository.FindAsync<EQU_COM_DEFINITION_TASK>(t =>
                t.OrderCode == planWorkOrder.OrderCode && t.OperationName == taskOptions.OperationId).Result.Count;
            EQU_COM_DEFINITION_TASK equComDefinitionTaskFind =
                 repository.Find<EQU_COM_DEFINITION_TASK>(t =>
                    t.OrderCode == planWorkOrder.OrderCode && t.OperationName == taskOptions.OperationId).OrderBy(t => t.CreateOn).FirstOrDefault();

            EQU_COM_DEFINITION_TASK equComDefinitionTask = new EQU_COM_DEFINITION_TASK();
            equComDefinitionTask.ActionSort = equComDefinitionTaskFind.ActionSort;
            equComDefinitionTask.TaskNo = equComDefinitionTaskFind.TaskNo + "-" + (count).ToString();
            equComDefinitionTask.MovePath_Id = equComDefinitionTaskFind.MovePath_Id;
            equComDefinitionTask.MovePathSub_Id = equComDefinitionTaskFind.MovePathSub_Id;
            equComDefinitionTask.Command = taskCode;
            equComDefinitionTask.Equipment_Id = equComDefinitionTaskFind.Equipment_Id;
            equComDefinitionTask.ActionEquipmentId = equComDefinitionTaskFind.ActionEquipmentId;
            equComDefinitionTask.SubPathNo = taskOptions.SubPathNo;
            equComDefinitionTask.EQUTask_Id = equTask.EQUTask_Id.ToString().ToUpper();
            equComDefinitionTask.Status = ((int)StatusAction.Executing).ToString();// "2";//执行中
            equComDefinitionTask.CreateBy = UserContext.Current.UserName;
            equComDefinitionTask.CreateOn = DateTime.Now;
            equComDefinitionTask.OperationName = taskOptions.OperationId;
            equComDefinitionTask.OrderCode = planWorkOrder.OrderCode;
            equComDefinitionTask.ExecuteStart = DateTime.Now;
            return equComDefinitionTask;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>

        public async Task<WebResponseContent> Faultlog(Equ_TaskReceive equ_TASKVM)
        {
            equ_TASKVM.Status = "4";//
            string msg = string.Empty;
            try
            {
                EQU_COM_DEFINITION_TASK eQU_COM_DEFINITION_TASK = null;
                List<EQU_FAULT_PHENOMENON> eQU_EQU_FAULT_PHENOMENON = null;
                List<EQU_COM_DEFINITION_TASK_RECORD> eQU_COM_DEFINITION_TASKList = new List<EQU_COM_DEFINITION_TASK_RECORD>();
                PROC_PROGRAM pROC_PROGRAM = null;
                var taskNo = equ_TASKVM.TaskNo;
                EQU_EQUIPMENT equmlAction = null;
                PLAN_WORK_ORDER plan_work_order = null;
                eQU_COM_DEFINITION_TASK = repository.Find<EQU_COM_DEFINITION_TASK>(t => t.TaskNo == taskNo).OrderByDescending(t => t.CreateOn).Where(t => t.TaskNo == taskNo).FirstOrDefault();
                //  eQU_COM_DEFINITION_TASK = //await repository.FindAsync<EQU_COM_DEFINITION_TASK>(t => t.TaskNo == taskNo).OrderByDescending(t => t.CreateOn).Where(t => t.TaskNo == taskNo).FirstOrDefault();
                if (eQU_COM_DEFINITION_TASK.Status == "2" || eQU_COM_DEFINITION_TASK.Status == "3" || eQU_COM_DEFINITION_TASK.Status == "4")//3完成 4异常
                {

                    eQU_EQU_FAULT_PHENOMENON = await repository.FindAsync<EQU_FAULT_PHENOMENON>(t => t.TaskNo == eQU_COM_DEFINITION_TASK.TaskNo.ToString());
                    if (eQU_EQU_FAULT_PHENOMENON == null)
                    {
                        Logger.Info(LoggerType.Login, "此次执行任务没有信息", webResponse.Message, msg);
                        webResponse.Data = "此次执行任务没有信息";
                        return webResponse.Error("此次执行任务没有信息");
                    }
                    var logli = eQU_EQU_FAULT_PHENOMENON.OrderByDescending(t => t.CreateOn).Select(t => new { t.Content, t.CreateOn });
                    //foreach (var item in logli)
                    //{

                    //   // webResponse.Data += item.Content + " 时间:" + item.CreateOn + "<br>"; // item.CreateOn+Environment.NewLine;
                    //}
                    webResponse.Data = eQU_EQU_FAULT_PHENOMENON.OrderByDescending(t => t.CreateOn).Select(t => new { t.Content, t.CreateOn });
                }
                Logger.Info(LoggerType.Success, equ_TASKVM.Serialize(), webResponse.Message, msg);
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                {
                    throw new Exception(ex.Message + ex.StackTrace);
                }
                Logger.Info(LoggerType.Exception, equ_TASKVM.Serialize(), webResponse.Message, msg);
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {
                Logger.Info(LoggerType.Login, equ_TASKVM.Serialize(), webResponse.Message, msg);
            }
        }
        public async Task<WebResponseContent> Sendlog(Equ_TaskReceive equ_TASKVM)
        {
            equ_TASKVM.Status = "3";//
            string msg = string.Empty;
            try
            {
                EQU_COM_DEFINITION_TASK eQU_COM_DEFINITION_TASK = null;
                EQU_COM_DEFINITION_TASK_RECORD eQU_COM_DEFINITION_TASK_RECORD = null;
                List<EQU_COM_DEFINITION_TASK_RECORD> eQU_COM_DEFINITION_TASKList = new List<EQU_COM_DEFINITION_TASK_RECORD>();
                PROC_PROGRAM pROC_PROGRAM = null;
                var taskNo = equ_TASKVM.TaskNo;
                EQU_EQUIPMENT equmlAction = null;
                PLAN_WORK_ORDER plan_work_order = null;
                eQU_COM_DEFINITION_TASK = repository.Find<EQU_COM_DEFINITION_TASK>(t => t.TaskNo == taskNo).OrderByDescending(t => t.CreateOn).Where(t => t.TaskNo == taskNo).FirstOrDefault();
                //  eQU_COM_DEFINITION_TASK = //await repository.FindAsync<EQU_COM_DEFINITION_TASK>(t => t.TaskNo == taskNo).OrderByDescending(t => t.CreateOn).Where(t => t.TaskNo == taskNo).FirstOrDefault();
                if (eQU_COM_DEFINITION_TASK.Status == "2" || eQU_COM_DEFINITION_TASK.Status == "3" || eQU_COM_DEFINITION_TASK.Status == "4")//3完成 4异常
                {

                    eQU_COM_DEFINITION_TASK_RECORD = await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK_RECORD>(t => t.ComDefintion_TaskId == eQU_COM_DEFINITION_TASK.ComDefintion_TaskId.ToString());
                    if (eQU_COM_DEFINITION_TASK_RECORD == null)
                    {
                        Logger.Info(LoggerType.Login, "此次执行任务没有信息", webResponse.Message, msg);
                        webResponse.Data = "此次执行任务没有信息";
                        return webResponse.Error("此次执行任务没有信息");
                    }
                    webResponse.Data = eQU_COM_DEFINITION_TASK_RECORD.SendLog;
                }
                Logger.Info(LoggerType.Success, equ_TASKVM.Serialize(), webResponse.Message, msg);
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                {
                    throw new Exception(ex.Message + ex.StackTrace);
                }
                Logger.Info(LoggerType.Exception, equ_TASKVM.Serialize(), webResponse.Message, msg);
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {
                Logger.Info(LoggerType.Login, equ_TASKVM.Serialize(), webResponse.Message, msg);
            }
        }

        public async Task<WebResponseContent> PlcGet(EQU_PLCConfig plcMl)
        {
            string msg = string.Empty;
            try
            {

                string ip = plcMl.PlcIP;// section["Ip"];
                var isConnect = IsIpConnect(ip);
                if (!isConnect)
                {
                    webResponse.Data = $"{ip}连接不上！";
                    return webResponse.Error($"{ip}连接不上！");

                }
                var isOpen = PlcHelper.Instance.OpenPlc(CpuType.S71500, 0, 1, ip);
                if (isOpen)
                {
                    if (plcMl.DbBlockType == "Receive")
                    {
                        if (plcMl.DataType == "Real")
                        {
                            //  var v1 = (double)PlcHelper.Instance.ReadReal(6, 0);//R角度
                            plcMl.CurrentValue = PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                        }
                        if (plcMl.DataType == "Word")
                        {
                            plcMl.CurrentValue = PlcHelper.Instance.ReadWord((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();

                        }
                        if (plcMl.DataType == "DWord")
                        {
                            plcMl.CurrentValue = PlcHelper.Instance.ReadDWord((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                        }
                        if (plcMl.DataType == "Byte")
                        {

                            var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                            plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                        }
                        if (plcMl.DataType == "Bit")
                        {
                            var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                            plcMl.CurrentValue = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                        }
                        repository.DbContext.Set<EQU_PLCConfig>().Update(plcMl);
                        repository.SaveChanges();
                    }

                    if (plcMl.DbBlockType == "Send" && !string.IsNullOrEmpty(plcMl.CurrentWriteValue))
                    {
                        if (plcMl.DataType == "Real")
                        {
                            PlcHelper.Instance.WriteReal((int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(plcMl.CurrentWriteValue));
                        }
                        if (plcMl.DataType == "Word")
                        {
                            //  UInt16 myUInt16 = (UInt16)Math.Abs((short)myInt16);
                            PlcHelper.Instance.WriteWord((int)plcMl.DbBlock, (int)plcMl.Offset, ushort.Parse(plcMl.CurrentWriteValue));
                        }
                        if (plcMl.DataType == "DWord")
                        {
                            PlcHelper.Instance.WriteDWord((int)plcMl.DbBlock, (int)plcMl.Offset, uint.Parse(plcMl.CurrentWriteValue));
                        }
                        if (plcMl.DataType == "Byte")
                        {
                            var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                            PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(plcMl.CurrentWriteValue));
                            plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                        }
                        if (plcMl.DataType == "Bit")
                        {
                            var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                            PlcHelper.Instance.WriteBool((int)plcMl.DbBlock, (int)plcMl.Offset, bool.Parse(plcMl.CurrentWriteValue), DataType.DataBlock, biAdr);
                            plcMl.CurrentValue = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                        }


                        repository.DbContext.Set<EQU_PLCConfig>().Update(plcMl);
                        repository.SaveChanges();
                    }
                    else
                    {
                        if (plcMl.DataType == "Byte")
                        {
                            var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                           // PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(plcMl.CurrentWriteValue));
                            plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                        }
                        if (plcMl.DataType == "Bit")
                        {
                            var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                            //PlcHelper.Instance.WriteBool((int)plcMl.DbBlock, (int)plcMl.Offset, bool.Parse(plcMl.CurrentWriteValue), DataType.DataBlock, biAdr);
                            plcMl.CurrentValue = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                        }


                        repository.DbContext.Set<EQU_PLCConfig>().Update(plcMl);
                        repository.SaveChanges();
                    }
                }



                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {


            }
            finally
            {
                PlcHelper.Instance.ClosePlc(PlcHelper.Instance.Plc);
            }
            webResponse.Data = "此次执行任务没有信息";
            return webResponse.Error("此次执行任务没有信息");



        }
        /// <summary>
        /// PLC当前值 （对刀仪) Auto
        /// </summary>
        /// <returns></returns>
        public async Task<WebResponseContent> PlcGetAuto()
        {
            var inteconfig = QueryInteConfigure("EquMeasureAuto");
            if (inteconfig == null)
            {
                webResponse.Data = $"测量仪配置没有开启！";
                return webResponse.Error($"测量仪配置没有开启！");
            }
            string msg = string.Empty;
            string rfidPlc = string.Empty;
            var isConnectUpdate1 = IsIpConnect("192.168.1.1");
            if (isConnectUpdate1 == false)
            {
                webResponse.Data = $"192.168.1.1 ping不通！";
                return webResponse.Error($"192.168.1.1 ping不通！");
            }
            var li = await repository.FindAsync<EQU_PLCConfig>(t => t.PlcIP == "192.168.1.190");
            try
            {
                var firstml = li.Where(t => t.PlcNameZH == "测量完成" && t.DbBlock == 150).FirstOrDefault();// section["Ip"];
                var ip = string.Empty;

                if (firstml != null)
                {
                    ip = firstml.PlcIP;
                    var isConnect = IsIpConnect(ip);
                    if (!isConnect)
                    {
                        webResponse.Data = $"{ip}连接不上！";
                        return webResponse.Error($"{ip}连接不上！");

                    }
                }
                var isOpen = PlcHelper.Instance.OpenPlc(CpuType.S71500, 0, 1, ip);

                foreach (var plcMl in li)
                {
                    if (plcMl.DbBlockType == "Receive")
                    {

                        if (plcMl.DataType == "DWord")
                        {


                            if (plcMl.PlcNameZH == "RFID" && plcMl.DbBlock == 150)
                            {
                                rfidPlc = plcMl.CurrentValue;
                            }


                        }


                    }
                }
                //写（传）模板
                if (rfidPlc != string.Empty)
                {
                    EQU_TOOL eQU_EQUIPMENT = null;
                    EQU_Holder eQU_Holder = null;///
                    EQU_ACCESSORY eQU_ACCESSORY1 = null;
                    EQU_ACCESSORY eQU_ACCESSORY2 = null;
                    EQU_ACCESSORY eQU_ACCESSORY3 = null;
                    var plcMStart = li.Where(t => t.PlcNameZH == "开始启动").FirstOrDefault();// section["Ip"];
                    eQU_EQUIPMENT = await repository.FindAsyncFirst<EQU_TOOL>(t => t.RfidCode == rfidPlc);
                    eQU_Holder = await repository.FindAsyncFirst<EQU_Holder>(t => t.Holder_Code == eQU_EQUIPMENT.handle_type);
                    eQU_ACCESSORY1 = await repository.FindAsyncFirst<EQU_ACCESSORY>(t => t.AccessorieCode == eQU_EQUIPMENT.Accessorie1Code);
                    eQU_ACCESSORY2 = await repository.FindAsyncFirst<EQU_ACCESSORY>(t => t.AccessorieCode == eQU_EQUIPMENT.Accessorie2Code);
                    eQU_ACCESSORY3 = await repository.FindAsyncFirst<EQU_ACCESSORY>(t => t.AccessorieCode == eQU_EQUIPMENT.Accessorie3_Code);
                    if (eQU_EQUIPMENT != null && plcMStart != null)
                    {

                        foreach (var plcMl in li)
                        {
                            if (plcMl.DbBlockType == "Send")
                            {
                                if (plcMl.DataType == "Real")
                                {
                                    if (plcMl.PlcNameZH == "刀长" && eQU_EQUIPMENT != null)
                                    {
                                        //MES给PLC 回传RFID值（DB150,X0.0）（包过刀具号，刀具长，刀柄号，刀柄长，加长杆1模版，加长杆1长，加长杆2模版，
                                        //加长杆2长，加长杆3模版，加长杆3长）并且发送 开始启动（DB100,X4.0）
                                        PlcHelper.Instance.WriteReal((int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_EQUIPMENT.knife_length.ToString()));
                                    }

                                    if (plcMl.PlcNameZH == "刀柄长" && eQU_Holder != null)
                                    {

                                        PlcHelper.Instance.WriteReal((int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_Holder.HolderL.ToString()));
                                    }

                                    //加长杆长1
                                    if (plcMl.PlcNameZH == "加长杆1长" && eQU_ACCESSORY1 != null)
                                    {

                                        PlcHelper.Instance.WriteReal((int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_ACCESSORY1.AceL.ToString()));
                                    }

                                    //加长杆长2
                                    if (plcMl.PlcNameZH == "加长杆2长" && eQU_ACCESSORY2 != null)
                                    {

                                        PlcHelper.Instance.WriteReal((int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_ACCESSORY2.AceL.ToString()));
                                    }

                                    //加长杆长3
                                    if (plcMl.PlcNameZH == "加长杆3长" && eQU_ACCESSORY3 != null)
                                    {

                                        PlcHelper.Instance.WriteReal((int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_ACCESSORY3.AceL.ToString()));
                                    }


                                }
                                if (plcMl.DataType == "DWord")
                                {
                                    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                    if (plcMl.PlcNameZH == "RFID" && eQU_EQUIPMENT != null)
                                    {
                                        //MES给PLC 回传RFID值（DB150,X0.0）（包过刀具号，刀具长，刀柄号，刀柄长，加长杆1模版，加长杆1长，加长杆2模版，
                                        //加长杆2长，加长杆3模版，加长杆3长）并且发送 开始启动（DB100,X4.0）
                                        PlcHelper.Instance.WriteDWord((int)plcMl.DbBlock, (int)plcMl.Offset, uint.Parse(eQU_EQUIPMENT.RfidCode));
                                    }

                                    plcMl.CurrentValue = PlcHelper.Instance.ReadDWord((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock).ToString();

                                }
                                if (plcMl.DataType == "Byte")
                                {
                                    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                    if (plcMl.PlcNameZH == "刀具模板号" && eQU_EQUIPMENT != null)
                                    {
                                        //MES给PLC 回传RFID值（DB150,X0.0）（包过刀具号，刀具长，刀柄号，刀柄长，加长杆1模版，加长杆1长，加长杆2模版，
                                        //加长杆2长，加长杆3模版，加长杆3长）并且发送 开始启动（DB100,X4.0）
                                        PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(eQU_EQUIPMENT.MeasureTemplate));
                                    }

                                    if (plcMl.PlcNameZH == "刀柄模板号" && eQU_Holder != null)
                                    {
                                        //MES给PLC 回传RFID值（DB150,X0.0）（包过刀具号，刀具长，刀柄号，刀柄长，加长杆1模版，加长杆1长，加长杆2模版，
                                        //加长杆2长，加长杆3模版，加长杆3长）并且发送 开始启动（DB100,X4.0）

                                        PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(eQU_Holder.MeasureTemplate));
                                    }

                                    if (plcMl.PlcNameZH == "加长杆1模板号" && eQU_ACCESSORY1 != null)
                                    {
                                        //MES给PLC 回传RFID值（DB150,X0.0）（包过刀具号，刀具长，刀柄号，刀柄长，加长杆1模版，加长杆1长，加长杆2模版，
                                        //加长杆2长，加长杆3模版，加长杆3长）并且发送 开始启动（DB100,X4.0）

                                        PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(eQU_ACCESSORY1.MeasureTemplate));
                                    }

                                    if (plcMl.PlcNameZH == "加长杆2模板号" && eQU_ACCESSORY2 != null)
                                    {
                                        PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(eQU_ACCESSORY2.MeasureTemplate));
                                    }

                                    if (plcMl.PlcNameZH == "加长杆3模板号" && eQU_ACCESSORY3 != null)
                                    {

                                        PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(eQU_ACCESSORY3.MeasureTemplate));
                                    }

                                    plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                                }

                                repository.DbContext.Set<EQU_PLCConfig>().Update(plcMl);
                                repository.SaveChanges();
                            }

                        }

                    }
                    else
                    {
                        Logger.Info(LoggerType.Login, "没有设备", webResponse.Message, msg);
                        return webResponse.Error("没有设备");
                    }
                }
                ////for 开始测量信号
                var countIsMeasure = await repository.FindAsync<EQU_PLCConfig>(t => t.PlcNameZH == "开始测量信号" && t.CurrentValue == "True");
                // var twoplc = li.Where(t => t.PlcNameZH == "RFID"&&t.DbBlock==150).FirstOrDefault();
                var twoTool = await repository.FindAsyncFirst<EQU_TOOL>(t => t.RfidCode == rfidPlc);
                if (countIsMeasure.Count > 0)
                {
                    twoTool.IsMeasure = "True";
                    var plcMl = li.Where(t => t.PlcNameZH == "RFID" && t.DbBlock == 100).FirstOrDefault(); //await repository.FindAsyncFirst<EQU_PLCConfig>(t => t.PlcNameZH == "RFID" && t.DbBlock == 100);
                    if (plcMl != null && plcMl.DataType == "DWord" && plcMl.DbBlock == 100)
                    {
                        var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                        PlcHelper.Instance.WriteDWord((int)plcMl.DbBlock, (int)plcMl.Offset, uint.Parse(rfidPlc));

                        plcMl.CurrentValue = rfidPlc;
                        repository.DbContext.Set<EQU_PLCConfig>().Update(plcMl);
                        repository.DbContext.Set<EQU_TOOL>().Update(twoTool);
                        repository.SaveChanges();
                    }

                }
                else
                {
                    twoTool.IsMeasure = "False";
                    repository.DbContext.Set<EQU_TOOL>().Update(twoTool);
                    repository.SaveChanges();
                }


                foreach (var plcMl in li)
                {
                    if (plcMl.DbBlockType == "Receive")
                    {

                        if (plcMl.DataType == "Real")
                        {
                            //  var v1 = (double)PlcHelper.Instance.ReadReal(6, 0);//R角度
                            plcMl.CurrentValue = PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                        }
                        if (plcMl.DataType == "DWord")
                        {

                            plcMl.CurrentValue = PlcHelper.Instance.ReadDWord((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                            if (plcMl.PlcNameZH == "RFID" && plcMl.DbBlock == 150)
                            {
                                rfidPlc = plcMl.CurrentValue;
                            }


                        }
                        if (plcMl.DataType == "Byte")
                        {

                            var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                            plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                        }
                        if (plcMl.DataType == "Bit")
                        {
                            var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                            if (plcMl.PlcNameZH == "测量完成" && plcMl.DbBlock == 150)
                            {
                                plcMl.CurrentValue = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                                if (plcMl.CurrentValue == "True")
                                {
                                    firstml.CurrentValue = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                                    repository.DbContext.Set<EQU_PLCConfig>().Update(plcMl);
                                    repository.SaveChanges();
                                }

                            }

                        }

                    }
                }



                var firstTool = await repository.FindAsyncFirst<EQU_TOOL>(t => t.RfidCode == rfidPlc);
                if (firstml.CurrentValue == "True")
                {//测量完成 
                 //MES读取各个数据
                 //1.对刀长度 = 刀具长度 + 刀柄长 + 加长杆长 总长必须[0, 3]
                 //2.刀头直径[0, 0.02] 刀长[0.02, 0.05] 刀摆[0.05, +]  报警（装错刀）
                 //3.R角 4.C角
                 //5.刀柄长[-3, 0.5]
                 //6.刀柄半径[-0.5, 0.5] 4.加长杆长[-3, 0.5]        5.加长杆直径[-1, 1]
                    decimal[] totallengthRange = new decimal[] { 0, 3 };//对刀长度new float[] { 0f, 3f };//对刀长度
                    decimal[] knifeDRange = new decimal[] { 0, 0.02m };//刀头直径
                    decimal[] knifeLengthRange = new decimal[] { 0m, 0.02m };//刀长
                    decimal[] holderLenghtRange = new decimal[] { -3m, 0.5m };//刀柄长
                    decimal[] holderRRange = new decimal[] { -0.5m, 0.5m };//刀柄半径
                    decimal[] aceLenghtRange = new decimal[] { -1m, 1m };//.加长杆直径
                    decimal reality_knife_length_PositiveNegative = 0;
                    decimal reality_knife_length_Diff = 0;
                    decimal holderLengthPositiveNegative = 0;
                    decimal holderDiff = 0;
                    decimal ace1LengthPositiveNegative = 0;
                    decimal ace1Diff = 0;
                    decimal ace2LengthPositiveNegative = 0;
                    decimal ace2Diff = 0;
                    decimal ace3LengthPositiveNegative = 0;
                    decimal ace3Diff = 0;
                    foreach (var plcMl in li)
                    {
                        if (plcMl.DbBlockType == "Receive")
                        {
                            if (plcMl.DataType == "Real")
                            {

                                if (plcMl.PlcNameZH == "刀具R角" && plcMl.DbBlock == 150)
                                {
                                    firstTool.reality_R = decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }
                                if (plcMl.PlcNameZH == "刀具直径" && plcMl.DbBlock == 150)
                                {
                                    firstTool.reality_knife_width = decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }
                                //1 刀具和中心线误差2 正   刀具和中心线误差 负
                                //   2刀具和中心线误差2 负   刀具和中心线误差 正
                                if (plcMl.PlcNameZH == "刀具和中心线误差2" && plcMl.DbBlock == 150)
                                {
                                    reality_knife_length_PositiveNegative = decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }
                                if (plcMl.PlcNameZH == "刀具和中心线误差" && plcMl.DbBlock == 150)
                                {
                                    reality_knife_length_Diff = decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }
                                if (plcMl.PlcNameZH == "刀具电机当前位置" && plcMl.DbBlock == 150)
                                {

                                }
                                if (plcMl.PlcNameZH == "刀柄半径" && plcMl.DbBlock == 150)
                                {
                                    firstTool.HolderBD = decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString()) * 2;
                                }
                                if (plcMl.PlcNameZH == "刀柄和中心线误差2" && plcMl.DbBlock == 150)
                                {
                                    holderLengthPositiveNegative = decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }
                                if (plcMl.PlcNameZH == "刀柄和中心线误差1" && plcMl.DbBlock == 150)
                                {
                                    holderDiff = decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }
                                if (plcMl.PlcNameZH == "刀柄电机当前位置" && plcMl.DbBlock == 150)
                                {
                                    decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }

                                if (plcMl.PlcNameZH == "加长杆1直径" && plcMl.DbBlock == 150)
                                {
                                    firstTool.Ace1D = decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }
                                if (plcMl.PlcNameZH == "加长杆1和中心线误差1" && plcMl.DbBlock == 150)
                                {
                                    ace1Diff = decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }
                                if (plcMl.PlcNameZH == "加长杆1和中心线误差2" && plcMl.DbBlock == 150)
                                {
                                    ace1LengthPositiveNegative = decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }
                                if (plcMl.PlcNameZH == "加长杆1电机当前位置" && plcMl.DbBlock == 150)
                                {
                                    decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }

                                if (plcMl.PlcNameZH == "加长杆2直径" && plcMl.DbBlock == 150)
                                {
                                    firstTool.Ace2D = decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }
                                if (plcMl.PlcNameZH == "加长杆2和中心线误差1" && plcMl.DbBlock == 150)
                                {
                                    ace2Diff = decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }
                                if (plcMl.PlcNameZH == "加长杆2和中心线误差2" && plcMl.DbBlock == 150)
                                {
                                    ace2LengthPositiveNegative = decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }
                                if (plcMl.PlcNameZH == "加长杆2电机当前位置" && plcMl.DbBlock == 150)
                                {
                                    decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }
                                //3
                                if (plcMl.PlcNameZH == "加长杆3直径" && plcMl.DbBlock == 150)
                                {
                                    firstTool.Ace3D = decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }
                                if (plcMl.PlcNameZH == "加长杆3和中心线误差1" && plcMl.DbBlock == 150)
                                {
                                    ace3Diff = decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }
                                if (plcMl.PlcNameZH == "加长杆3和中心线误差2" && plcMl.DbBlock == 150)
                                {
                                    ace3LengthPositiveNegative = decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }
                                if (plcMl.PlcNameZH == "加长杆3电机当前位置" && plcMl.DbBlock == 150)
                                {
                                    decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }

                                if (plcMl.PlcNameZH == "刀具实际长度" && plcMl.DbBlock == 150)
                                {
                                    firstTool.reality_knife_length = decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }
                                if (plcMl.PlcNameZH == "刀柄实际长度" && plcMl.DbBlock == 150)
                                {
                                    firstTool.HolderL = decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }
                                if (plcMl.PlcNameZH == "加长杆1实际长度" && plcMl.DbBlock == 150)
                                {
                                    firstTool.Ace1L = decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }
                                if (plcMl.PlcNameZH == "加长杆2实际长度" && plcMl.DbBlock == 150)
                                {
                                    firstTool.Ace2L = decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }
                                if (plcMl.PlcNameZH == "加长杆3实际长度" && plcMl.DbBlock == 150)
                                {
                                    firstTool.Ace3L = decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }
                                plcMl.CurrentValue = PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                            }
                            if (plcMl.DataType == "DWord")
                            {
                                plcMl.CurrentValue = PlcHelper.Instance.ReadDWord((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                            }
                            if (plcMl.DataType == "Byte")
                            {

                                var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                            }
                            if (plcMl.DataType == "Bit")
                            {
                                var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                plcMl.CurrentValue = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                            }

                            repository.DbContext.Set<EQU_PLCConfig>().Update(plcMl);
                            repository.SaveChanges();
                        }
                    }

                    if (reality_knife_length_PositiveNegative > 0)
                    {
                        reality_knife_length_Diff = -Math.Abs(reality_knife_length_Diff);
                    }
                    else
                    {
                        reality_knife_length_Diff = Math.Abs(reality_knife_length_Diff);
                    }
                    firstTool.reality_knife_length = firstTool.reality_knife_length + reality_knife_length_Diff;
                    if (Math.Abs(firstTool.reality_knife_length.Value - firstTool.knife_length.Value) < totallengthRange[1])
                    {
                        firstTool.IsKnifeLengthRange = "True";
                    }
                    else
                    {
                        firstTool.IsKnifeLengthRange = "False";
                    }

                    if (holderLengthPositiveNegative > 0)
                    {
                        holderDiff = -Math.Abs(holderDiff);
                    }
                    else
                    {
                        holderDiff = Math.Abs(holderDiff);
                    }
                    firstTool.HolderL = firstTool.HolderL + holderDiff;
                    if (Math.Abs(firstTool.HolderLTheory.Value - firstTool.HolderL.Value) < holderLenghtRange[1])
                    {
                        firstTool.IsHolderLenghtRange = "True";
                    }
                    else
                    {
                        firstTool.IsHolderLenghtRange = "False";
                    }


                    if (ace1LengthPositiveNegative > 0)
                    {
                        ace1Diff = -Math.Abs(ace1Diff);
                    }
                    else
                    {
                        ace1Diff = Math.Abs(ace1Diff);
                    }
                    firstTool.Ace1L = firstTool.Ace1L + ace1Diff;
                    if (Math.Abs(firstTool.Ace1LTheory.Value - firstTool.Ace1L.Value) < aceLenghtRange[1])
                    {
                        firstTool.IsAce1LenghtRange = "True";
                    }
                    else
                    {
                        firstTool.IsAce1LenghtRange = "False";
                    }

                    if (ace2LengthPositiveNegative > 0)
                    {
                        ace2Diff = -Math.Abs(ace2Diff);
                    }
                    else
                    {
                        ace2Diff = Math.Abs(ace2Diff);
                    }
                    firstTool.Ace2L = firstTool.Ace2L + ace2Diff;
                    if (Math.Abs(firstTool.Ace2LTheory.Value - firstTool.Ace2L.Value) < aceLenghtRange[1])
                    {
                        firstTool.IsAce2LenghtRange = "True";
                    }
                    else
                    {
                        firstTool.IsAce2LenghtRange = "False";
                    }

                    if (ace3LengthPositiveNegative > 0)
                    {
                        ace3Diff = -Math.Abs(ace3Diff);
                    }
                    else
                    {
                        ace3Diff = Math.Abs(ace3Diff);
                    }
                    firstTool.Ace3L = firstTool.Ace3L + ace3Diff;
                    if (Math.Abs(firstTool.Ace3LTheory.Value - firstTool.Ace3L.Value) < aceLenghtRange[1])
                    {
                        firstTool.IsAce3LenghtRange = "True";
                    }
                    else
                    {
                        firstTool.IsAce3LenghtRange = "False";
                    }

                    repository.DbContext.Set<EQU_TOOL>().Update(firstTool);
                    repository.SaveChanges();
                }





                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {


            }
            finally
            {
                PlcHelper.Instance.ClosePlc(PlcHelper.Instance.Plc);
            }
            webResponse.Data = "此次执行任务没有信息";
            return webResponse.Error("此次执行任务没有信息");

        }
        /// <summary>
        /// 工件写入RFID
        /// </summary>
        /// <returns></returns>
        public async Task<WebResponseContent> PlcWorkpieceRFID([FromBody] PlcWorkpieceRFID pLAN_WORK)
        {
            Equ_TASKVM equ_TASKVM1 = new Equ_TASKVM();
            //var isConnectUpdate1 = IsIpConnect("192.168.1.160");
            //if (isConnectUpdate1 == false)
            //{
            //    webResponse.Data = $"192.168.1.160 ping不通！";
            //    return webResponse.Error($"192.168.1.1 ping不通！");
            //}
            string msg = string.Empty;
            string rfidPlc = string.Empty;
            var procMaterilFirst = await repository.FindAsyncFirst<PROC_MATERIAL>(t => t.Id.ToString() == pLAN_WORK.Id.ToString().ToUpper());
            var plan_work_order = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.Order_Id.ToString() == pLAN_WORK.Order_Id.ToString().ToUpper());

            if (plan_work_order == null)
            {
                webResponse.Data = $"没找到工单！";
                return webResponse.Error($"没找到工单！");
            }
            var eQU_COM_DEFINITION_TASK = await repository.FindAsyncFirst<EQU_COM_DEFINITION_TASK>(t => t.OrderCode == plan_work_order.OrderCode && t.Command == "TASK001");
            if (eQU_COM_DEFINITION_TASK == null)
            {
                webResponse.Data = $"此工件不需要写RFID！";
                return webResponse.Error($"此工件不需要写RFID！");
            }
            try
            {

                Guid equipment_Id = Guid.Parse(eQU_COM_DEFINITION_TASK.Equipment_Id.ToString());
                Guid eQUTask_Id = Guid.Parse(eQU_COM_DEFINITION_TASK.EQUTask_Id);
                var equmlcnc = await repository.FindAsyncFirst<EQU_EQUIPMENT>(t => t.Id == equipment_Id);

                FormattableString formattableString =
                $"select s.* from INTE_SHELVES s where  exists (select 1 from  INTE_WAREHOUSE w where w.WarehouseCode='A001' and s.WarehouseId=w.Id) and s.INTE_SHELVES_Id not in (select SHELVES_Id from PROC_CALL_MATERIAL pm where pm.SHELVES_Id is not null)";


                var iNTE_SHELVES = await repository.DbContext.Set<INTE_SHELVES>().FromSqlInterpolated<INTE_SHELVES>(formattableString).Select(s => new
                {
                    s.INTE_SHELVES_Id
                }).FirstOrDefaultAsync();

                equ_TASKVM1.Command = "TASK001";
                equ_TASKVM1.Unit = equmlcnc.unit == null ? 1 : equmlcnc.unit.Value;

                int indexSplit = 3;//默认2
                var inteconfig = QueryInteConfigure("IndexSplit");
                if (inteconfig == null)
                {
                    //webResponse.Data = $"测量仪配置没有开启！";
                    //return webResponse.Error($"测量仪配置没有开启！");
                    indexSplit = 3;
                }
                else { indexSplit =int.Parse(inteconfig.ConfigureParam); }
              
                equ_TASKVM1.WorkOrderCode =SplitEx(plan_work_order.OrderCode, indexSplit);//调度id

                procMaterilFirst.RfidCode = DateTime.Now.ToString("yy") + SplitEx(plan_work_order.OrderCode, indexSplit);//调度id

                //写RFID 分配库位
                procMaterilFirst.PlanStart = plan_work_order.PlanStart;
                procMaterilFirst.PlanEnd = plan_work_order.PlanEnd;
                var pROC_CALL_MATERIAL = repository.DbContext.Set<PROC_CALL_MATERIAL>().Where(t => t.Order_Id == procMaterilFirst.Order_Id && t.WorkpieceCode == procMaterilFirst.workpiece_name).FirstOrDefault();
                if (iNTE_SHELVES != null)
                {

                    procMaterilFirst.StorageState = "入库";
                    procMaterilFirst.SHELVES_Id = iNTE_SHELVES.INTE_SHELVES_Id.ToString().ToUpper();
                    procMaterilFirst.LastUpdateOn = DateTime.Now;

                    if (pROC_CALL_MATERIAL != null)
                    {
                        pROC_CALL_MATERIAL.PlanStart = plan_work_order.PlanStart;
                        pROC_CALL_MATERIAL.PlanEnd = plan_work_order.PlanEnd;
                        pROC_CALL_MATERIAL.StorageState = "入库";
                        pROC_CALL_MATERIAL.SHELVES_Id = iNTE_SHELVES.INTE_SHELVES_Id.ToString().ToUpper();
                        pROC_CALL_MATERIAL.LastUpdateOn = DateTime.Now;
                        repository.DbContext.Set<PROC_CALL_MATERIAL>().Update(pROC_CALL_MATERIAL);
                    }
                }

                repository.DbContext.Set<PROC_MATERIAL>().Update(procMaterilFirst);
                eQU_COM_DEFINITION_TASK.ActionEquipmentId = equmlcnc.Id.ToString().ToUpper();
                eQU_COM_DEFINITION_TASK.Status = ((int)StatusAction.Completed).ToString(); ;//// ((int)StatusAction.Executing).ToString();// "2";//执行中
                eQU_COM_DEFINITION_TASK.ExecuteStart = DateTime.Now;
                repository.DbContext.Set<EQU_COM_DEFINITION_TASK>().Update(eQU_COM_DEFINITION_TASK);
                repository.SaveChanges();
                webResponse.Data = equ_TASKVM1.Serialize();
                //MQ_Send
                //SendTaskToMQ(equmlcnc, eQU_COM_DEFINITION_TASK);




                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {

                webResponse.Data = "失败";
                return webResponse.Error(ex.Message);
            }
            finally
            {
                PlcHelper.Instance.ClosePlc(PlcHelper.Instance.Plc);
            }
            //webResponse.Data = "此次执行任务没有信息";
            //return webResponse.OK("成功"+ procMaterilFirst.RfidCode);

        }
        /// <summary>
        /// 刀具写入RFID 不发指令
        /// </summary>
        /// <param name="pLAN_WORK"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> PlcToolRFIDNoSend([FromBody] PlcToolRFID pLAN_WORK)
        {
            Equ_TASKVM equ_TASKVM1 = new Equ_TASKVM();
            var eQU_COM_DEFINITION_TASK = new EQU_COM_DEFINITION_TASK();
            var isConnectUpdate1 = IsIpConnect("192.168.1.160");
            if (isConnectUpdate1 == false)
            {
                webResponse.Data = $"192.168.1.160 ping不通！";
                return webResponse.Error($"192.168.1.1 ping不通！");
            }
            string msg = string.Empty;
            string rfidPlc = string.Empty;
            var eQU_TOOLMeasure = await repository.FindAsyncFirst<EQU_TOOL_Measure>(t => t.tool_name != null);
            var eQU_TOOL = await repository.FindAsyncFirst<EQU_TOOL>(t => t.Identifier == pLAN_WORK.Identifier && t.program_seq == pLAN_WORK.program_seq);
            var program = await repository.FindAsyncFirst<PROC_PROGRAM>(t => t.Identifier == pLAN_WORK.Identifier && t.sequence == pLAN_WORK.program_seq);
            //await repository.FindAsyncFirst<EQU_TOOL>(t => t.Identifier.ToString() == pLAN_WORK.Identifier.ToString());
            var li190 = await repository.FindAsync<EQU_PLCConfig>(t => (t.PlcNameZH == "对刀仪准备启动BT40" || t.PlcNameZH == "对刀仪准备启动A63") && t.DbBlockType == "Send");
            eQU_COM_DEFINITION_TASK.OrderCode = pLAN_WORK.Identifier;
            eQU_COM_DEFINITION_TASK.Command = "TASK001";

            var wAREHOUSE = await repository.FindAsyncFirst<INTE_WAREHOUSE>(t => t.WarehouseNameZH.Contains("中央刀库"));
            var shelvelist = await repository.FindAsync<INTE_SHELVES>(t => t.ShelfNameZH.Contains("中央刀库货架A") && t.WarehouseId.Equals(wAREHOUSE.Id.ToString().ToUpper()));

            //分配库位点
            var eq = eQU_TOOL.HolderTypeId;
            var count = shelvelist.OrderBy(t => t.DBCode).Where(t => t.HolderTypeId == eq && t.Status == "True").Count();
            
            //测量调度
            EQU_COM_DEFINITION_TASK_DETECTION eQU_COM_DEFINITION_TASK_DETECTION = new EQU_COM_DEFINITION_TASK_DETECTION();
            try
            {
                EQU_EQUIPMENT equmlcnc = new EQU_EQUIPMENT();
                equ_TASKVM1.Command = "TASK001";
                equ_TASKVM1.Unit = 1;//equmlcnc.unit == null ? 1 : equmlcnc.unit.Value;
                equ_TASKVM1.WorkOrderCode = DateTime.Now.ToString("yy") + SplitEx(pLAN_WORK.Identifier, 2) + $"{pLAN_WORK.program_seq}";//调度id
                if (eQU_TOOL != null)
                {
                    eQU_COM_DEFINITION_TASK_DETECTION.OrderCode = pLAN_WORK.Identifier;
                    eQU_COM_DEFINITION_TASK_DETECTION.Command = "TASK001";
                    eQU_COM_DEFINITION_TASK_DETECTION.TaskNo = pLAN_WORK.Identifier + eQU_TOOL.program_seq;
                    eQU_COM_DEFINITION_TASK_DETECTION.Status = ((int)StatusAction.Completed).ToString();// "2";//执行中
                    eQU_COM_DEFINITION_TASK_DETECTION.ExecuteStart = DateTime.Now;
                    eQU_COM_DEFINITION_TASK_DETECTION.ProgramId = program.Id.ToString().ToUpper();
                    eQU_COM_DEFINITION_TASK_DETECTION.LastUpdateOn = DateTime.Now;
                    eQU_COM_DEFINITION_TASK_DETECTION.Description = "【" + equ_TASKVM1.WorkOrderCode + "】【" + equ_TASKVM1.Unit + "】";
                    eQU_COM_DEFINITION_TASK_DETECTION.ToolId = eQU_TOOL.Id.ToString().ToUpper();
                    repository.DbContext.Set<EQU_COM_DEFINITION_TASK_DETECTION>().Add(eQU_COM_DEFINITION_TASK_DETECTION);

                    eQU_TOOL.RfidCode = equ_TASKVM1.WorkOrderCode;
                    eQU_TOOL.LastUpdateOn = DateTime.Now;
                    eQU_TOOL.MeasureStartTime=DateTime.Now;
                    repository.DbContext.Set<EQU_TOOL>().Update(eQU_TOOL);
                    repository.SaveChanges();
                    if (eQU_TOOLMeasure != null)
                    {
                        eQU_TOOLMeasure.HolderTypeId = eQU_TOOL.HolderTypeId;
                        eQU_TOOLMeasure.RfidCode = eQU_TOOL.RfidCode;
                        eQU_TOOLMeasure.tool_name = eQU_TOOL.tool_name;
                        eQU_TOOLMeasure.Identifier = eQU_TOOL.Identifier;
                        eQU_TOOLMeasure.Holder_Code = eQU_TOOL.Holder_Code;
                        eQU_TOOLMeasure.handle_type = eQU_TOOL.handle_type;
                        eQU_TOOLMeasure.TogetherSeq = 0;
                        repository.DbContext.Set<EQU_TOOL_Measure>().Update(eQU_TOOLMeasure);
                        repository.SaveChanges();
                        webResponse.Status = true;
                    }

                }
                webResponse.Data = equ_TASKVM1.Serialize();
                ////MQ_Send
                //SendTaskToMQ(equmlcnc, eQU_COM_DEFINITION_TASK);
             
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                webResponse.Status = false;
                webResponse.Data = "失败";
                return webResponse.Error("失败");

            }
            finally
            {
                //  PlcHelper.Instance.ClosePlc(PlcHelper.Instance.Plc);
            }
            webResponse.Status = false;
            webResponse.Data = "失败";
            return webResponse.Error("失败");

        }
        /// <summary>
        /// 刀具写入RFID
        /// </summary>
        /// <param name="pLAN_WORK"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> PlcToolRFID([FromBody] PlcToolRFID pLAN_WORK)
        {
            Equ_TASKVM equ_TASKVM1 = new Equ_TASKVM();
            var eQU_COM_DEFINITION_TASK = new EQU_COM_DEFINITION_TASK();
            var isConnectUpdate1 = IsIpConnect("192.168.1.160");
            //if (isConnectUpdate1 == false)
            //{
            //    webResponse.Data = $"192.168.1.160 ping不通！";
            //    return webResponse.Error($"192.168.1.1 ping不通！");
            //}
            string msg = string.Empty;
            string rfidPlc = string.Empty;
            var eQU_TOOLMeasure = await repository.FindAsyncFirst<EQU_TOOL_Measure>(t => t.tool_name != null);
            var eQU_TOOL = await repository.FindAsyncFirst<EQU_TOOL>(t => t.Identifier == pLAN_WORK.Identifier && t.program_seq == pLAN_WORK.program_seq);
            var program = await repository.FindAsyncFirst<PROC_PROGRAM>(t => t.Identifier == pLAN_WORK.Identifier && t.sequence == pLAN_WORK.program_seq);
            //await repository.FindAsyncFirst<EQU_TOOL>(t => t.Identifier.ToString() == pLAN_WORK.Identifier.ToString());
            var li190 = await repository.FindAsync<EQU_PLCConfig>(t => (t.PlcNameZH == "对刀仪准备启动BT40" || t.PlcNameZH == "对刀仪准备启动A63")&&t.DbBlockType=="Send");
            eQU_COM_DEFINITION_TASK.OrderCode = pLAN_WORK.Identifier;
            eQU_COM_DEFINITION_TASK.Command = "TASK001";

            var wAREHOUSE = await repository.FindAsyncFirst<INTE_WAREHOUSE>(t => t.WarehouseNameZH.Contains("中央刀库"));
            var shelvelist = await repository.FindAsync<INTE_SHELVES>(t => t.ShelfNameZH.Contains("中央刀库货架A") && t.WarehouseId.Equals(wAREHOUSE.Id.ToString().ToUpper()));

            //分配库位点
            var eq = eQU_TOOL.HolderTypeId;
            var count = shelvelist.OrderBy(t => t.DBCode).Where(t => t.HolderTypeId == eq && t.Status == "True").Count();
            if (count == 0)
            {
                eQU_TOOLMeasure.Description = $"中央刀库！{eQU_TOOL.HolderTypeId}暂无库位";
                if (eQU_TOOLMeasure != null)
                {

                    repository.DbContext.Set<EQU_TOOL_Measure>().Update(eQU_TOOLMeasure);
                    repository.DbContext.SaveChanges();
                }
                webResponse.Data = $"中央刀库！{eQU_TOOL.HolderTypeId}暂无库位";
                return webResponse.Error($"中央刀库！{eQU_TOOL.HolderTypeId}暂无库位");
            }

            //测量调度
            EQU_COM_DEFINITION_TASK_DETECTION eQU_COM_DEFINITION_TASK_DETECTION = new EQU_COM_DEFINITION_TASK_DETECTION();
            try
            {
                webResponse.Status = false;
                EQU_EQUIPMENT equmlcnc = new EQU_EQUIPMENT();
                equ_TASKVM1.Command = "TASK001";
                equ_TASKVM1.Unit = 1;//equmlcnc.unit == null ? 1 : equmlcnc.unit.Value;
                equ_TASKVM1.WorkOrderCode = DateTime.Now.ToString("yy") + SplitEx(pLAN_WORK.Identifier, 2) + $"{pLAN_WORK.program_seq}";//调度id
                if (eQU_TOOL != null)
                {
                    eQU_COM_DEFINITION_TASK_DETECTION.OrderCode = pLAN_WORK.Identifier;
                    eQU_COM_DEFINITION_TASK_DETECTION.Command = "TASK001";
                    eQU_COM_DEFINITION_TASK_DETECTION.TaskNo = pLAN_WORK.Identifier + eQU_TOOL.program_seq;
                    eQU_COM_DEFINITION_TASK_DETECTION.Status = ((int)StatusAction.Completed).ToString();// "2";//执行中
                    eQU_COM_DEFINITION_TASK_DETECTION.ExecuteStart = DateTime.Now;
                    eQU_COM_DEFINITION_TASK_DETECTION.ProgramId = program.Id.ToString().ToUpper();
                    eQU_COM_DEFINITION_TASK_DETECTION.LastUpdateOn = DateTime.Now;
                    eQU_COM_DEFINITION_TASK_DETECTION.Description = "【" + equ_TASKVM1.WorkOrderCode + "】【" + equ_TASKVM1.Unit + "】";
                    eQU_COM_DEFINITION_TASK_DETECTION.ToolId = eQU_TOOL.Id.ToString().ToUpper();
                    repository.DbContext.Set<EQU_COM_DEFINITION_TASK_DETECTION>().Add(eQU_COM_DEFINITION_TASK_DETECTION);

                    eQU_TOOL.RfidCode = equ_TASKVM1.WorkOrderCode;
                    eQU_TOOL.LastUpdateOn = DateTime.Now;
                    eQU_TOOL.MeasureStartTime= DateTime.Now;
                    repository.DbContext.Set<EQU_TOOL>().Update(eQU_TOOL);
                    repository.SaveChanges();
                    if (eQU_TOOLMeasure!=null)
                    {
                        eQU_TOOLMeasure.HolderTypeId = eQU_TOOL.HolderTypeId;
                        eQU_TOOLMeasure.RfidCode = eQU_TOOL.RfidCode;
                        eQU_TOOLMeasure.tool_name=eQU_TOOL.tool_name;
                        eQU_TOOLMeasure.Identifier = eQU_TOOL.Identifier;
                        eQU_TOOLMeasure.Holder_Code= eQU_TOOL.Holder_Code;
                        eQU_TOOLMeasure.handle_type= eQU_TOOL.handle_type;
                        eQU_TOOLMeasure.TogetherSeq = 0;
                        eQU_TOOLMeasure.Description = "开始测量";
                        repository.DbContext.Set<EQU_TOOL_Measure>().Update(eQU_TOOLMeasure);
                        repository.SaveChanges();
                        webResponse.Status = true;
                    }
                    
                }
                webResponse.Data = equ_TASKVM1.Serialize();
                var eQU_TOOLMeasurenew = await repository.FindAsyncFirst<EQU_TOOL_Measure>(t => t.tool_name != null);
                ////MQ_Send
                //SendTaskToMQ(equmlcnc, eQU_COM_DEFINITION_TASK);
                if (webResponse.Status==true&& eQU_TOOLMeasurenew.RfidCode== eQU_TOOL.RfidCode)
                {
                  //  return SetToolPlcPaly(eQU_TOOL, li190);
                }
                else
                {
                    webResponse.Status = false;
                    webResponse.Data = "失败";
                    return webResponse.Error("失败");
                }

                webResponse.Status = false;
               // webResponse.Data = "OK";
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                webResponse.Status = false;
                webResponse.Data = "失败";
                return webResponse.Error("失败");

            }
            finally
            {
              //  PlcHelper.Instance.ClosePlc(PlcHelper.Instance.Plc);
            }
            //webResponse.Status = false;
            //webResponse.Data = "失败";
            //return webResponse.Error("失败");

        }
        /// <summary>
        /// 对刀仪移动BT40或A63
        /// </summary>
        /// <param name="eQU_TOOL"></param>
        /// <param name="li190"></param>
        /// <returns></returns>
        public WebResponseContent SetToolPlcPaly(EQU_TOOL eQU_TOOL, List<EQU_PLCConfig> li190)
        {
            try
            {
                var ip = string.Empty;
                if (li190 != null)
                {
                    ip = li190.FirstOrDefault().PlcIP;

                }

                var isOpen = false;// PlcHelper190.Instance.OpenPlc(CpuType.S71500, 0, 1, ip);
                if (isOpen == false)
                {
                    S7.Net.Plc plc = PlcHelper190.Instance.Plc;
                    if (plc == null)
                    {
                        isOpen = PlcHelper190.Instance.OpenPlc(CpuType.S71500, 0, 1, ip);
                        plc = PlcHelper190.Instance.Plc;
                    }
                    if (plc.IsConnected)
                    {
                        isOpen = true;
                        if (isOpen == true)
                        {

                            foreach (var plcMl3 in li190)
                            {
                                if (plcMl3.DbBlockType == "Send")
                                {
                                    if (plcMl3.DataType == "Bit")
                                    {
                                        var biAdr = GetDecimalPlacesAsInteger((double)plcMl3.Offset.Value, 1);
                                        if (plcMl3.PlcNameZH == "对刀仪准备启动BT40" && eQU_TOOL.HolderTypeId == "BT40")
                                        {
                                            plc.WriteBit(DataType.DataBlock, (int)plcMl3.DbBlock, (int)plcMl3.Offset, biAdr, true);

                                            Thread.Sleep(200); // 模拟工作
                                        }
                                        if (plcMl3.PlcNameZH == "对刀仪准备启动A63" && eQU_TOOL.HolderTypeId == "A63")
                                        {
                                            plc.WriteBit(DataType.DataBlock, (int)plcMl3.DbBlock, (int)plcMl3.Offset, biAdr, true);
                                            Thread.Sleep(200); // 模拟工作

                                        }


                                    }
                                }

                            }
                        }
                    }
                    else
                    {
                        plc.Open();
                        isOpen = true;
                        if (isOpen == true)
                        {

                            foreach (var plcMl3 in li190)
                            {
                                if (plcMl3.DbBlockType == "Send")
                                {
                                    if (plcMl3.DataType == "Bit")
                                    {
                                        var biAdr = GetDecimalPlacesAsInteger((double)plcMl3.Offset.Value, 1);
                                        if (plcMl3.PlcNameZH == "对刀仪准备启动BT40" && eQU_TOOL.HolderTypeId == "BT40")
                                        {
                                            plc.WriteBit(DataType.DataBlock, (int)plcMl3.DbBlock, (int)plcMl3.Offset, biAdr, true);

                                            Thread.Sleep(200); // 模拟工作
                                        }
                                        if (plcMl3.PlcNameZH == "对刀仪准备启动A63" && eQU_TOOL.HolderTypeId == "A63")
                                        {
                                            plc.WriteBit(DataType.DataBlock, (int)plcMl3.DbBlock, (int)plcMl3.Offset, biAdr, true);
                                            Thread.Sleep(200); // 模拟工作

                                        }


                                    }
                                }

                            }
                        }


                    }
                }


                // Logger.Info(LoggerType.Success, res.Serialize(), webResponse.Message, msg);
                //  webResponse.Data = res;
                //  return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {

                webResponse.Status = false;
                webResponse.Data = "失败";
                return webResponse.Error("失败");
            }
            finally
            {
                //  PlcHelper190.Instance.ClosePlc(PlcHelper190.Instance.Plc);
            }
            webResponse.Status = false;
            webResponse.Data = "OK";
            return webResponse.OK(ResponseType.Success);
        }

        public int GetDecimalPlacesAsInteger(double value, int numberOfDecimalPlaces)
        {
            string decimalPart = value.ToString("F" + numberOfDecimalPlaces).Split('.')[1];
            int integerValue = int.Parse(decimalPart);
            return integerValue;
        }

        #region by guoyuguo 2024.12.19 检测仪
        /// <summary>
        /// 检测仪启动
        /// </summary>
        /// <param name="eQU_TOOL"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<WebResponseContent> PlcStart(EQU_TOOL eQU_TOOL)
        {

            var isConnectUpdate1 = IsIpConnect("192.168.1.1");
            if (isConnectUpdate1 == false)
            {
                webResponse.Data = $"192.168.1.1 ping不通！";
                return webResponse.Error($"192.168.1.1 ping不通！");
            }
            string msg = string.Empty;
            var li = await repository.FindAsync<EQU_PLCConfig>(t => t.PlcIP == "192.168.1.190");
            var li3config = await repository.FindAsync<EQU_PLCConfig>(t => t.PlcIP == "192.168.1.3");
            EQU_TOOL eQU_Tool = null;
            EQU_Holder eQU_Holder = null;///
            EQU_ACCESSORY eQU_ACCESSORY1 = null;
            EQU_ACCESSORY eQU_ACCESSORY2 = null;
            EQU_ACCESSORY eQU_ACCESSORY3 = null;
            PROC_PROGRAM pROGRAM = null;
            EQU_ToolModel eQU_ToolModel = null;
            EQU_COM_DEFINITION_TASK_DETECTION eQU_COM_DEFINITION_TASK_DETECTION = null;
            PlcHelper plcHelper = new PlcHelper();
            PlcHelper plcHelper3 = new PlcHelper();
            try
            {
                var wAREHOUSE = await repository.FindAsyncFirst<INTE_WAREHOUSE>(t => t.WarehouseNameZH.Contains("中央刀库"));
                var shelvelist = await repository.FindAsync<INTE_SHELVES>(t => t.ShelfNameZH.Contains("中央刀库货架A") && t.WarehouseId.Equals(wAREHOUSE.Id.ToString().ToUpper()));
                var plcMStart = li.Where(t => t.PlcNameZH == "开始启动").FirstOrDefault();// section["Ip"];
                eQU_Tool = await repository.FindAsyncFirst<EQU_TOOL>(t => t.Id == eQU_TOOL.Id);
                if (eQU_Tool != null)
                {
                    eQU_ToolModel = await repository.FindAsyncFirst<EQU_ToolModel>(t => t.ToolModel_Code == eQU_Tool.tool_name);
                }
                pROGRAM = await repository.FindAsyncFirst<PROC_PROGRAM>(t => t.Identifier == eQU_TOOL.Identifier && t.sequence == eQU_TOOL.program_seq);
                eQU_Holder = await repository.FindAsyncFirst<EQU_Holder>(t => t.Holder_Code == eQU_Tool.handle_type);
                eQU_ACCESSORY1 = await repository.FindAsyncFirst<EQU_ACCESSORY>(t => t.AccessorieCode == eQU_Tool.Accessorie1Code);
                eQU_ACCESSORY2 = await repository.FindAsyncFirst<EQU_ACCESSORY>(t => t.AccessorieCode == eQU_Tool.Accessorie2Code);
                eQU_ACCESSORY3 = await repository.FindAsyncFirst<EQU_ACCESSORY>(t => t.AccessorieCode == eQU_Tool.Accessorie3_Code);
                if (eQU_Tool != null && plcMStart != null)
                {
                    var ip = string.Empty;

                    if (plcMStart != null)
                    {
                        ip = plcMStart.PlcIP;
                        var isConnect = IsIpConnect(ip);
                        if (!isConnect)
                        {
                            webResponse.Data = $"{ip}连接不上！";
                            return webResponse.Error($"{ip}连接不上！");

                        }
                    }

                    plcHelper.Plc = new Plc(CpuType.S71500, ip, 0, 1);
                    S7.Net.Plc plc = plcHelper.Plc;
                    if (plcHelper.Plc.IsConnected)
                    { }
                    else
                    {
                        plcHelper.Plc.Open();
                    }
                    Thread.Sleep(200); // 
                    var startCheck = false;
                    var rfidplc = string.Empty;
                    //1.检查测量准备就绪
                    var isMeasure = false;
                    var list = li.ToList();
                    List<string> arry1 = new List<string>();
                    arry1.Add("开始测量信号");
                    arry1.Add("测量完成");
                    arry1.Add("RFID");

                    var licheck1 = list.Where(t => t.DbBlockType == "Receive" && arry1.Contains(t.PlcNameZH)).ToList();
                    foreach (var plcMl in licheck1)
                    {
                        if (plcMl.DbBlockType == "Receive")
                        {
                            if (plcMl.DataType == "DWord")
                            {
                                if (plcMl.PlcNameZH == "RFID" && plcHelper.Plc.IsConnected == true)
                                {
                                    rfidplc = plcHelper.ReadDWord((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock).ToString();

                                }
                            }
                            if (plcMl.DataType == "Bit")
                            {
                                if (plcMl.PlcNameZH == "开始测量信号" && plcHelper.Plc.IsConnected == true)
                                {
                                    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                                    startCheck = plcHelper.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString()));

                                }
                                if (plcMl.PlcNameZH == "测量完成" && plcHelper.Plc.IsConnected == true)
                                {
                                    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                                    isMeasure = plcHelper.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString()));
                                }
                            }

                        }
                    }
                    //2.发送数据MES给PLC
                    if (startCheck)
                    {
                        List<string> arry = new List<string>();
                        arry.Add("刀具模板号");
                        arry.Add("刀柄模板号");
                        arry.Add("加长西杆1模板号");
                        arry.Add("加长杆2模板号");
                        arry.Add("加长杆3模板号");
                        arry.Add("刀长");
                        var licheck = list.Where(t => t.DbBlockType == "Send" && arry.Contains(t.PlcNameZH)).ToList();

                        foreach (var plcMl in licheck)
                        {

                            if (plcMl.DbBlockType == "Send")
                            {

                                if(plcMl.DataType=="Word")
                                {

                                    if (plcMl.PlcNameZH == "刀具模板号")
                                    {
                                        var rfid = eQU_ToolModel != null ? eQU_ToolModel.MeasureTemplate : eQU_Tool.MeasureTemplate;//eQU_TOOL.RfidCode;
                                                                                                                                    //   PlcHelper.Instance.WriteDWord((int)plcMl.DbBlock, (int)plcMl.Offset, uint.Parse(rfid));
                                        plc.Write(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, ushort.Parse(rfid));
                                        Thread.Sleep(200); // 模拟工作
                                    }
                                    if (plcMl.PlcNameZH == "刀柄模板号")
                                    {
                                        var rfid = eQU_Holder != null? eQU_Holder.MeasureTemplate:"";//eQU_TOOL.RfidCode;
                                                                                                                                    //   PlcHelper.Instance.WriteDWord((int)plcMl.DbBlock, (int)plcMl.Offset, uint.Parse(rfid));
                                        plc.Write(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, ushort.Parse(rfid));
                                        Thread.Sleep(200); // 模拟工作
                                    }
                                    if (plcMl.PlcNameZH == "加长西杆1模板号")
                                    {
                                        var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                        //   PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(eQU_ACCESSORY1.MeasureTemplate));
                                        if (plc.IsConnected == true && eQU_ACCESSORY1 != null)
                                        {
                                            var rfid = eQU_ACCESSORY1.MeasureTemplate;

                                            plc.Write(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, ushort.Parse(rfid));
                                            Thread.Sleep(200); // 模拟工作
                                        }
                                        // plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "加长杆2模板号")
                                    {

                                        var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                        if (plc.IsConnected == true && eQU_ACCESSORY2 != null)
                                        {
                                            //PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(eQU_ACCESSORY2.MeasureTemplate));
                                            var rfid =eQU_ACCESSORY2.MeasureTemplate;

                                            plc.Write(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, ushort.Parse(rfid));
                                            Thread.Sleep(200); // 模拟工作
                                        }
                                        // plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "加长杆3模板号")
                                    {

                                        var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                        if (plc.IsConnected == true && eQU_ACCESSORY3 != null)
                                        {
                                            var rfid = eQU_ACCESSORY3.MeasureTemplate;

                                            plc.Write(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, ushort.Parse(rfid));
                                            Thread.Sleep(200); // 模拟工作
                                        }
                                        // PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(eQU_ACCESSORY3.MeasureTemplate));
                                        // plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                                    }

                                }
                                if (plcMl.DataType == "Byte")
                                {

                                    if (plcMl.PlcNameZH == "刀具模板号")
                                    {
                                        var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);


                                        if (plc.IsConnected == true && eQU_Tool != null)
                                        {
                                            var bytenew = eQU_ToolModel!=null?byte.Parse( eQU_ToolModel.MeasureTemplate): byte.Parse(eQU_Tool.MeasureTemplate);//  byte.Parse(biAdr.ToString());

                                            plc.WriteBytes(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, new byte[] { bytenew });
                                            Thread.Sleep(200); // 模拟工作
                                        }

                                        //  plc.WriteBytes(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, new byte[] { bytenew });
                                        //  PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(eQU_EQUIPMENT.MeasureTemplate),(S7.Net.DataType)biAdr);
                                        //   plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                                    }

                                    if (plcMl.PlcNameZH == "刀柄模板号")
                                    {
                                        var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                                        //    PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, new byte[] { bytenew });
                                        if (plc.IsConnected == true && eQU_Holder != null)
                                        {
                                            var bytenew = byte.Parse(eQU_Holder.MeasureTemplate);
                                            plc.WriteBytes(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, new byte[] { bytenew });
                                            Thread.Sleep(200); // 模拟工作
                                        }
                                        //  plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "加长西杆1模板号")
                                    {
                                        var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                        //   PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(eQU_ACCESSORY1.MeasureTemplate));
                                        if (plc.IsConnected == true && eQU_ACCESSORY1 != null)
                                        {
                                            var bytenew = byte.Parse(eQU_ACCESSORY1.MeasureTemplate);

                                            plc.WriteBytes(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, new byte[] { bytenew });
                                            Thread.Sleep(200); // 模拟工作
                                        }
                                        // plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "加长杆2模板号")
                                    {

                                        var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                        if (plc.IsConnected == true && eQU_ACCESSORY2 != null)
                                        {
                                            //PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(eQU_ACCESSORY2.MeasureTemplate));
                                            var bytenew = byte.Parse(eQU_ACCESSORY2.MeasureTemplate);

                                            plc.WriteBytes(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, new byte[] { bytenew });
                                            Thread.Sleep(200); // 模拟工作
                                        }
                                        // plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "加长杆3模板号")
                                    {

                                        var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                        if (plc.IsConnected == true && eQU_ACCESSORY3 != null)
                                        {
                                            var bytenew = byte.Parse(eQU_ACCESSORY3.MeasureTemplate);

                                            plc.WriteBytes(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, new byte[] { bytenew });
                                            Thread.Sleep(200); // 模拟工作
                                        }
                                        // PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(eQU_ACCESSORY3.MeasureTemplate));
                                        // plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                                    }

                                }

                                if (plcMl.PlcNameZH == "刀长" && eQU_Tool != null)
                                {
                                    // PlcHelper.Instance.WriteReal((int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(plcMl.CurrentWriteValue));

                                    //    PlcHelper.Instance.WriteReal((int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_EQUIPMENT.knife_length.ToString()));
                                    if (plc.IsConnected == true)
                                    {

                                        plc.Write(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_Tool.knife_length.ToString()));
                                        Thread.Sleep(200); // 模拟工作
                                    }
                                }
                                if (plcMl.PlcNameZH == "刀柄长" && eQU_Holder != null)
                                {
                                    //PlcHelper.Instance.WriteReal((int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_Holder.HolderL.ToString()));
                                    if (plc.IsConnected == true)
                                    {
                                        plc.Write(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_Holder.HolderL.ToString()));
                                        Thread.Sleep(200); // 模拟工作
                                    }
                                }
                                if (plcMl.PlcNameZH == "加长杆长1" && eQU_ACCESSORY1 != null)
                                {
                                    PlcHelper.Instance.WriteReal((int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_ACCESSORY1.AceL.ToString()));
                                    if (plc.IsConnected == true)
                                    {

                                        plc.Write(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_ACCESSORY1.AceL.ToString()));
                                        Thread.Sleep(200); // 模拟工作
                                    }
                                }
                                if (plcMl.PlcNameZH == "加长杆长2" && eQU_ACCESSORY2 != null)
                                {
                                    // PlcHelper.Instance.WriteReal((int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_ACCESSORY2.AceL.ToString()));
                                    if (plc.IsConnected == true)
                                    {

                                        plc.Write(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_ACCESSORY2.AceL.ToString()));
                                        Thread.Sleep(200); // 模拟工作
                                    }
                                }
                                if (plcMl.PlcNameZH == "加长杆长3" && eQU_ACCESSORY3 != null)
                                {
                                    // PlcHelper.Instance.WriteReal((int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_ACCESSORY3.AceL.ToString()));
                                    if (plc.IsConnected == true)
                                    {

                                        plc.Write(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_ACCESSORY3.AceL.ToString()));
                                        Thread.Sleep(200); // 模拟工作
                                    }
                                }


                                //repository.DbContext.Set<EQU_PLCConfig>().Update(plcMl);
                                //repository.SaveChanges();
                            }

                        }
                        List<string> arry2 = new List<string>();
                        arry2.Add("开始启动");
                        arry2.Add("RFIDMES到PLC");
                        var li2 = li.Where(t => t.DbBlockType == "Send" && arry2.Contains(t.PlcNameZH)).ToList();

                        foreach (var plcMl in li2)
                        {

                            if (plcMl.DbBlockType == "Send")
                            {
                                if (plcMl.DataType == "Bit")
                                {
                                    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                    if (plcMl.PlcNameZH == "开始启动")
                                    {
                                        plc.WriteBit(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, biAdr, true);

                                        Thread.Sleep(200); // 模拟工作
                                    }
                                    //  plcMl.CurrentValue = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                                }
                                if (plcMl.DataType == "DWord")
                                {
                                    if (plcMl.PlcNameZH == "RFIDMES到PLC")
                                    {
                                        var rfid = rfidplc;//eQU_TOOL.RfidCode;
                                                           //   PlcHelper.Instance.WriteDWord((int)plcMl.DbBlock, (int)plcMl.Offset, uint.Parse(rfid));

                                        plc.Write(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, uint.Parse(rfid));
                                        Thread.Sleep(200); // 模拟工作
                                    }
                                }
                            }
                        }

                        eQU_COM_DEFINITION_TASK_DETECTION = new EQU_COM_DEFINITION_TASK_DETECTION();
                        eQU_COM_DEFINITION_TASK_DETECTION.OrderCode = eQU_TOOL.Identifier;
                        eQU_COM_DEFINITION_TASK_DETECTION.Command = "TC008";
                        eQU_COM_DEFINITION_TASK_DETECTION.TaskNo = eQU_TOOL.Identifier + eQU_TOOL.program_seq;
                        eQU_COM_DEFINITION_TASK_DETECTION.Status = ((int)StatusAction.Completed).ToString();// "2";//执行中
                        eQU_COM_DEFINITION_TASK_DETECTION.ExecuteStart = DateTime.Now;
                        eQU_COM_DEFINITION_TASK_DETECTION.ProgramId = pROGRAM.Id.ToString().ToUpper();
                        eQU_COM_DEFINITION_TASK_DETECTION.LastUpdateOn = DateTime.Now;
                        eQU_COM_DEFINITION_TASK_DETECTION.Description = "【" + eQU_TOOL.Identifier + "】【" + eQU_TOOL.program_seq + "】";
                        eQU_COM_DEFINITION_TASK_DETECTION.ToolId = eQU_TOOL.Id.ToString().ToUpper();


                    }
                    //3.测量完成

                    PlcReceive plcReceive = new PlcReceive();
                    if (isMeasure == true)
                    {
                        //读取测量结果PLC                   
                        foreach (var plcMl in li)
                        {
                            if (plcMl.DbBlockType == "Receive")
                            {
                                if (plcMl.DataType == "Real")
                                {
                                    if (plcMl.PlcNameZH == "刀具R角")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                        eQU_Tool.R = decimal.Parse(plcMl.CurrentValue);
                                    }
                                    if (plcMl.PlcNameZH == "刀具直径")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                        eQU_Tool.reality_knife_width = decimal.Parse(plcMl.CurrentValue);
                                    }
                                    if (plcMl.PlcNameZH == "刀具和中心线误差")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "刀具和中心线误差2")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "刀具电机 当前位置")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "刀柄半径")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                        eQU_Holder.HolderBD = decimal.Parse(plcMl.CurrentValue);
                                    }
                                    if (plcMl.PlcNameZH == "刀柄和中心线误差1")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "刀柄和中心线误差2")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "刀柄电机当前位置")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "加长杆1直径")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "加长杆1和中心线误差1")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "加长杆1和中心线误差2")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "加长杆1电机当前位置")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "加长杆2直径")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "加长杆2和中心线误差1")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "加长杆2和中心线误差2")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "加长杆2电机当前位置")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "加长杆3直径")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "加长杆3和中心线误差1")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "加长杆3和中心线误差2")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "加长杆3和电机当前位置")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "刀具实际长度")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "刀柄实际长度")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "加长杆1实际长度")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "加长杆2实际长度")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                    }
                                    if (plcMl.PlcNameZH == "加长杆3实际长度")
                                    {
                                        plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                    }

                                }

                            }

                        }
                        //4.判断结果入库或退库
                        var isInOut = "In";
                        List<string> arry4 = new List<string>();
                        arry4.Add("请求退库");
                        arry4.Add("允许入库");
                        var li4 = li.Where(t => t.DbBlockType == "Send" && arry4.Contains(t.PlcNameZH)).ToList();
                        foreach (var plcMl in li4)
                        {
                            if (plcMl.DbBlockType == "Send")
                            {
                                if (plcMl.DataType == "Bit")
                                {
                                    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                    if (plcMl.PlcNameZH == "请求退库" && isInOut == "Out")
                                    {
                                        plcHelper.WriteBool((int)plcMl.DbBlock, (int)plcMl.Offset, true, DataType.DataBlock, biAdr);
                                        isInOut = "Out";
                                    }
                                    if (plcMl.PlcNameZH == "允许入库" && isInOut == "In")
                                    {
                                        plcHelper.WriteBool((int)plcMl.DbBlock, (int)plcMl.Offset, true, DataType.DataBlock, biAdr);
                                        isInOut = "In";
                                    }
                                }
                            }

                        }
                        //5.入库位置或退库
                        var location = 30;
                        List<string> arry5 = new List<string>();
                        arry5.Add("放刀位置编号");
                        arry5.Add("取bt40刀");
                        arry5.Add("取A63刀");
                        var li5 = li3config.Where(t => t.DbBlockType == "Send" && arry5.Contains(t.PlcNameZH)).ToList();
                        plcHelper3.Plc = new Plc(CpuType.S71500, li5.FirstOrDefault().PlcIP, 0, 1);
                        if (plcHelper3.Plc.IsConnected)
                        { }
                        else
                        {
                            plcHelper3.Plc.Open();
                        }
                        var eq = eQU_TOOL.HolderTypeId;
                        var shelf = shelvelist.Where(t => t.HolderTypeId == eq && t.Status == "True").FirstOrDefault();
                        if (shelf != null)
                        {
                            location = shelf.DBCode.Value;
                        }
                        Thread.Sleep(1000);
                        foreach (var plcMl in li5)
                        {
                            if (plcMl.DbBlockType == "Send")
                            {
                                if (plcMl.DataType == "Word")
                                {
                                    if (plcMl.PlcNameZH == "放刀位置编号")
                                    {
                                        eQU_Tool.RfidCode = rfidplc;
                                        plcMl.CurrentWriteValue = location.ToString(); //"30";
                                        eQU_Tool.location = location;
                                        plcHelper3.WriteWord((int)plcMl.DbBlock, (int)plcMl.Offset, ushort.Parse(location.ToString()));
                                    }
                                }
                            }
                        }
                        foreach (var plcMl in li5)
                        {
                            if (plcMl.DbBlockType == "Send")
                            {

                                if (plcMl.DataType == "Bit")
                                {//HolderTypeId
                                    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                    if (plcMl.PlcNameZH == "取bt40刀" && eQU_TOOL.HolderTypeId == "BT40")
                                    {
                                        plcHelper3.WriteBool((int)plcMl.DbBlock, (int)plcMl.Offset, true, DataType.DataBlock, biAdr);
                                    }
                                    else if (plcMl.PlcNameZH == "取A63刀" && eQU_TOOL.HolderTypeId == "A63")
                                    {
                                        plcHelper3.WriteBool((int)plcMl.DbBlock, (int)plcMl.Offset, true, DataType.DataBlock, biAdr);
                                    }
                                }
                            }
                        }

                        eQU_COM_DEFINITION_TASK_DETECTION = new EQU_COM_DEFINITION_TASK_DETECTION();
                        eQU_COM_DEFINITION_TASK_DETECTION.OrderCode = eQU_TOOL.Identifier;
                        eQU_COM_DEFINITION_TASK_DETECTION.Command = "TC009";
                        eQU_COM_DEFINITION_TASK_DETECTION.TaskNo = eQU_TOOL.Identifier + eQU_TOOL.program_seq;
                        eQU_COM_DEFINITION_TASK_DETECTION.Status = ((int)StatusAction.Completed).ToString();// "2";//执行中
                        eQU_COM_DEFINITION_TASK_DETECTION.ExecuteStart = DateTime.Now;
                        eQU_COM_DEFINITION_TASK_DETECTION.Description = "【" + eQU_TOOL.HolderTypeId + "】【" + eQU_Tool.location + "】";

                    }

                }
                WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
                {
                    if (eQU_Tool != null)
                    {
                        repository.DbContext.Set<EQU_TOOL>().Update(eQU_Tool);
                        repository.DbContext.SaveChanges();
                    }
                    if (eQU_COM_DEFINITION_TASK_DETECTION != null)
                    {
                        repository.DbContext.Set<EQU_COM_DEFINITION_TASK_DETECTION>().Add(eQU_COM_DEFINITION_TASK_DETECTION);
                        repository.DbContext.SaveChanges();
                    }
                    return webResponse.OK(ResponseType.Success);
                });
                Logger.Info(LoggerType.Success, eQU_Tool.Serialize(), webResponse.Message, msg);
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                Logger.Info(LoggerType.Exception, eQU_Tool.Serialize(), webResponse.Message, msg);
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {
                plcHelper.ClosePlc(plcHelper.Plc);
                plcHelper3.ClosePlc(plcHelper3.Plc);
            }
        }
        /// <summary>
        /// 检测仪启动 多次 只允许192.168.1.3
        /// </summary>
        /// <param name="eQU_TOOL"></param>
        /// <returns></returns>
        public async Task<WebResponseContent> PlcStartMulti(IHubContext<ChatHub> _hubContext)
        {            
            var inteconfig = QueryInteConfigure("EquMeasureAuto");
            if (inteconfig == null)
            {
                webResponse.Data = $"测量仪配置没有开启！";
                return webResponse.Error($"测量仪配置没有开启！");
            }
            var isConnectUpdate1 = IsIpConnect("192.168.1.3");
            if (isConnectUpdate1 == false)
            {
                webResponse.Data = $"192.168.1.3 ping不通！";
                return webResponse.Error($"192.168.1.3 ping不通！");
            }
            //设备使能锁
            List<string> emptyEqusEable = null;// new List<string>() { "JCR_001", "SLK_001",  "FNK_001", "SLL_001" };//SLK_002
            var equsEableLock = QueryInteConfigure("EqusEableLock");
            if (equsEableLock != null)
            {
                emptyEqusEable = equsEableLock.ConfigureParam.Split(",").ToList();
            }

            if (equsEableLock != null)
            {
                var Equs = await repository.FindAsync<EQU_EQUIPMENT>(t => emptyEqusEable.Contains(t.EquipmentCode));
                if (Equs != null)
                {
                    foreach (var itemEquipment in Equs)
                    {
                        if (itemEquipment.IsEnable != true)
                        {
                            //Logger.Info(LoggerType.Login, "设备未就绪", webResponse.Message, "设备未就绪");
                            await _hubContext.Clients.All.SendAsync("ShowMsg1", new MsgInfo { Title = ":", MsgContent = $"设备未就绪:" + itemEquipment.EquipmentNameZH });
                            webResponse.Data = $"设备未就绪:" + itemEquipment.EquipmentNameZH; 
                            return webResponse.Error($"设备未就绪:" + itemEquipment.EquipmentNameZH);
                        }
                    }
                }

            }
            //设备锁
            List<string> emptyEqus = null;// new List<string>() { "JCR_001", "SLK_001",  "FNK_001", "SLL_001" };//SLK_002
            var equsLock = QueryInteConfigure("EqusLock");
            if (equsLock != null)
            {
                emptyEqus = equsLock.ConfigureParam.Split(",").ToList();
            }
            //1.获取设备信息 没有设备执行任务
            if (equsLock != null)
            {
                var Equs = await repository.FindAsync<EQU_EQUIPMENT>(t => emptyEqus.Contains(t.EquipmentCode));
                if (Equs != null)
                {
                    foreach (var itemEquipment in Equs)
                    {
                        if (itemEquipment.StateCode != 1)
                        {
                            // Logger.Info(LoggerType.Login, "设备正运行", webResponse.Message, "设备正运行");
                            //   msgError += "设备正运行:" + itemEquipment.EquipmentNameZH;
                            await _hubContext.Clients.All.SendAsync("ShowMsg1", new MsgInfo { Title = ":", MsgContent = $"设备正运行:" + itemEquipment.EquipmentNameZH });
                            webResponse.Data = $"设备正运行:" + itemEquipment.EquipmentNameZH; 
                            return webResponse.Error($"设备正运行:" + itemEquipment.EquipmentNameZH);
                        }
                    }
                }

            }

            string msg = string.Empty;
            var li = await repository.FindAsync<EQU_PLCConfig>(t => t.PlcIP == "192.168.1.190");
            var li3config = await repository.FindAsync<EQU_PLCConfig>(t => t.PlcIP == "192.168.1.3");
            INTE_SHELVES shelf = null;
            EQU_TOOL eQU_Tool = null;
            EQU_Holder eQU_Holder = null;///
            EQU_ACCESSORY eQU_ACCESSORY1 = null;
            EQU_ACCESSORY eQU_ACCESSORY2 = null;
            EQU_ACCESSORY eQU_ACCESSORY3 = null;
            EQU_ToolModel eQU_ToolModel = null;
            EQU_TOOL_Measure eQU_TOOL_Measure = null;
            PlcHelper plcHelper = new PlcHelper();
            PlcHelper plcHelper3 = new PlcHelper();
            var location = 0;
            var isPlayKnifeComplete2 = false;
            var wAREHOUSE = await repository.FindAsyncFirst<INTE_WAREHOUSE>(t => t.WarehouseNameZH.Contains("中央刀库"));
            var shelvelist = await repository.FindAsync<INTE_SHELVES>(t => t.ShelfNameZH.Contains("中央刀库货架A") && t.WarehouseId.Equals(wAREHOUSE.Id.ToString().ToUpper()));
            eQU_TOOL_Measure = await repository.FindAsyncFirst<EQU_TOOL_Measure>(t => t.tool_name != null && t.RfidCode != "" && t.TogetherSeq >= 0);
            if (true)
            {
                List<string> arry6 = new List<string>();
                arry6.Add("放刀完成");
                var li5 = li3config.Where(t => arry6.Contains(t.PlcNameZH)).ToList();
                plcHelper3.Plc = new Plc(CpuType.S71500, li5.FirstOrDefault().PlcIP, 0, 1);
                if (plcHelper3.Plc.IsConnected)
                { }
                else
                {
                    plcHelper3.Plc.Open();
                }

                foreach (var plcMl in li5)
                {
                    if (plcMl.DbBlockType == "Receive")
                    {
                        if (plcMl.DataType == "Bit")
                        {
                            if (plcMl.PlcNameZH == "放刀完成")
                            {
                                var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                isPlayKnifeComplete2 = plcHelper3.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString()));
                              

                            }
                        }
                    }
                }
                plcHelper3.ClosePlc(plcHelper3.Plc);

             //   var eq = eQU_Tool.HolderTypeId;
             //   shelf = shelvelist.OrderBy(t => t.DBCode).Where(t => t.HolderTypeId == eq && t.DBCode == eQU_TOOL_Measure.location).FirstOrDefault();
                if ( isPlayKnifeComplete2 == true)
                //if (shelf != null )
                {
                    eQU_Tool = await repository.FindAsyncFirst<EQU_TOOL>(t => t.RfidCode == eQU_TOOL_Measure.RfidCode);
                    if (true)
                    {
                       // List<string> arry6 = new List<string>();
                        arry6.Add("放刀完成");
                     //   var li5 = li3config.Where(t => arry6.Contains(t.PlcNameZH)).ToList();
                        plcHelper3.Plc = new Plc(CpuType.S71500, li5.FirstOrDefault().PlcIP, 0, 1);
                        if (plcHelper3.Plc.IsConnected)
                        { }
                        else
                        {
                            plcHelper3.Plc.Open();
                        }

                        foreach (var plcMl in li5)
                        {
                            if (plcMl.DbBlockType == "Receive")
                            {
                                if (plcMl.DataType == "Bit")
                                {
                                    if (plcMl.PlcNameZH == "放刀完成")
                                    {
                                        var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                        plcHelper3.WriteBool((int)plcMl.DbBlock, (int)plcMl.Offset, false, DataType.DataBlock, biAdr);
                                        eQU_TOOL_Measure.IsInOut = "End";
                                        eQU_TOOL_Measure.Description = "入库完成！";
                                        eQU_Tool.MeasureEndTime = DateTime.Now;
                                    }
                                }
                            }
                        }
                        plcHelper3.ClosePlc(plcHelper3.Plc);

                    }
                    await _hubContext.Clients.All.SendAsync("ShowMsg1", new MsgInfo { Title = ":", MsgContent = $"入库完成！" });
                    //repository.DbContext.Set<INTE_SHELVES>().Update(shelf);
                    //repository.DbContext.SaveChanges();
                }

            }
            
            if (eQU_TOOL_Measure != null)
            {
                if(eQU_TOOL_Measure.IsKnifeCompleted =="True")
                {
                    eQU_TOOL_Measure.RfidCode = "";
                    eQU_TOOL_Measure.TogetherSeq = -1;
                    repository.DbContext.Set<EQU_TOOL_Measure>().Update(eQU_TOOL_Measure);
                    repository.DbContext.Set<EQU_TOOL>().Update(eQU_Tool);
                    repository.DbContext.SaveChanges();
                }
            }
            else
            {

                webResponse.Data = $"没有找到测量信息！";
                return webResponse.Error($"没有找到测量信息！");
            }



            var plcMStart = li.Where(t => t.PlcNameZH == "开始启动").FirstOrDefault();// section["Ip"];
            try
            {
                var ip = string.Empty;
                if (plcMStart != null)
                {
                    ip = plcMStart.PlcIP;
                    Thread.Sleep(200); // 
                    var isConnect = IsIpConnect(ip);
                    if (!isConnect)
                    {
                        //if (eQU_TOOL_Measure != null)
                        //{
                        //    eQU_TOOL_Measure.Description = $"{ip}连接不上！";
                        //    repository.DbContext.Set<EQU_TOOL_Measure>().Update(eQU_TOOL_Measure);
                        //    repository.DbContext.SaveChanges();
                        //}
                        webResponse.Data = $"{ip}连接不上！";
                        return webResponse.Error($"{ip}连接不上！");

                    }
                }
                plcHelper.Plc = new Plc(CpuType.S71500, ip, 0, 1);
                S7.Net.Plc plc = plcHelper.Plc;
                if (plcHelper.Plc.IsConnected)
                { }
                else
                {
                    plcHelper.Plc.Open();
                }
                Thread.Sleep(200); // 

                if (true)
                {
                    List<string> arry8 = new List<string>();
                    arry8.Add("中央刀库异常");
                    arry8.Add("放刀位置编号");
                    arry8.Add("刀库异常编号");
                    arry8.Add("放刀完成");
                    arry8.Add("放刀中");
                    var li5 = li3config.Where(t => arry8.Contains(t.PlcNameZH)).ToList();
                    plcHelper3.Plc = new Plc(CpuType.S71500, li5.FirstOrDefault().PlcIP, 0, 1);
                    if (plcHelper3.Plc.IsConnected)
                    { }
                    else
                    {
                        plcHelper3.Plc.Open();
                    }

                    foreach (var plcMl in li5)
                    {
                        if (plcMl.DbBlockType == "Receive")
                        {
                            if (plcMl.DataType == "Word")
                            {

                                if (plcMl.PlcNameZH == "刀库异常编号")
                                {
                                    //        UInt16 myUInt16 = (UInt16)Math.Abs((short)myInt16);

                                    eQU_TOOL_Measure.FaultNo = plcHelper3.ReadWord((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                }
                                if (plcMl.PlcNameZH == "放刀位置编号")
                                {
                                    eQU_TOOL_Measure.KnifeLocationNumber = plcHelper3.ReadWord((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                                }//对刀仪异常编码


                            }
                            if (plcMl.DataType == "Bit")
                            {
                                if (plcMl.PlcNameZH == "放刀完成")
                                {
                                    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                   var isPlayKnifeComplete1 = plcHelper3.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString()));
                                    // 设置运行状态
                                    eQU_TOOL_Measure.IsKnifeCompleted = isPlayKnifeComplete1.ToString();

                                }
                                if (plcMl.PlcNameZH == "放刀中")
                                {
                                    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                    var IsKnifeOngoing1 = plcHelper3.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString()));
                                    // 设置运行状态
                                    eQU_TOOL_Measure.IsKnifeOngoing = IsKnifeOngoing1.ToString();

                                }
                                if (plcMl.PlcNameZH == "中央刀库异常")
                                {
                                    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                    var IsFalut1 = plcHelper3.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString()));
                                    // 设置运行状态
                                    eQU_TOOL_Measure.IsFalut = IsFalut1.ToString();

                                }
                            }
                        }
                    }
                    plcHelper3.ClosePlc(plcHelper3.Plc);

                }

                var startCheck = false;
                var rfidplc = string.Empty;
                rfidplc = eQU_TOOL_Measure.RfidCode;
                var rfidplcWrite = string.Empty;
                //1.检查测量准备就绪
                bool isMeasure;
                List<EQU_PLCConfig> list;
                checkReadyMeasure( eQU_TOOL_Measure,li, plcHelper, ref startCheck, ref rfidplcWrite, out isMeasure, out list);
                if(startCheck==true)
                {
                    eQU_TOOL_Measure.TogetherSeq = 1;
                }
               
              
                eQU_Tool = await repository.FindAsyncFirst<EQU_TOOL>(t => t.RfidCode == rfidplc);
               

                if (eQU_Tool == null)
                {
                    if (eQU_TOOL_Measure != null)
                    {
                        eQU_TOOL_Measure.Description = $"没有找到刀具信息！{rfidplc}";
                        repository.DbContext.Set<EQU_TOOL_Measure>().Update(eQU_TOOL_Measure);
                        repository.DbContext.SaveChanges();
                    }
                    webResponse.Data = $"没有找到刀具信息！{rfidplc}";
                    return webResponse.Error($"没有找到刀具信息！{rfidplc}");
                }
                if (eQU_Tool != null)
                {
                    eQU_ToolModel= await repository.FindAsyncFirst<EQU_ToolModel>(t => t.ToolModel_Code == eQU_Tool.tool_name);
                }
              
                eQU_Holder = await repository.FindAsyncFirst<EQU_Holder>(t => t.Holder_Code == eQU_Tool.handle_type);
                eQU_ACCESSORY1 = await repository.FindAsyncFirst<EQU_ACCESSORY>(t => t.AccessorieCode == eQU_Tool.Accessorie1Code);
                eQU_ACCESSORY2 = await repository.FindAsyncFirst<EQU_ACCESSORY>(t => t.AccessorieCode == eQU_Tool.Accessorie2Code);
                eQU_ACCESSORY3 = await repository.FindAsyncFirst<EQU_ACCESSORY>(t => t.AccessorieCode == eQU_Tool.Accessorie3_Code);
                //2.发送数据MES给PLC
                if (startCheck&&eQU_TOOL_Measure.TogetherSeq>=1&& eQU_TOOL_Measure.TogetherSeq<2)
                {
                    eQU_TOOL_Measure.TogetherSeq = 2;
                    string outmes = string.Empty;
                    outmes = "";
                    StartCheckSendData(li, eQU_Tool, eQU_ToolModel, eQU_Holder, eQU_ACCESSORY1, eQU_ACCESSORY2, eQU_ACCESSORY3, plc, rfidplc, list,out outmes);
                    if (outmes != "")
                    {
                        eQU_TOOL_Measure.Description = $"{outmes}";
                        repository.DbContext.Set<EQU_TOOL_Measure>().Update(eQU_TOOL_Measure);
                        repository.DbContext.SaveChanges();
                        webResponse.Data = $"{outmes}";
                        return webResponse.Error($"{outmes}");
                    }
                   
                }
               
                //  // 创建队列实例
                //var taskQueue = new SingleTaskQueue();
                //    // 模拟并发添加任务
                //    Parallel.For(0, 10, i =>
                //    {
                //        taskQueue.Enqueue(() =>
                //        {
                //            Console.WriteLine($"开始处理任务 {i}");
                //            Thread.Sleep(1000); // 模拟耗时操作
                //            Console.WriteLine($"完成处理任务 {i}");
                //        });
                //    });
                var isPlayKnifeComplete = false;//放刀完成
                var isPlanyKnifeLoading = true;       //放刀中
               bool isIn = false;
                //3.测量完成

                if (isMeasure == true && eQU_TOOL_Measure.TogetherSeq == 2)
                {
                    eQU_TOOL_Measure.TogetherSeq = 3;
                    //List<string> arry4 = new List<string>();

                    //arry4.Add("允许入库");
                    //var li4 = li.Where(t => t.DbBlockType == "Send" && arry4.Contains(t.PlcNameZH)).ToList();
                    //foreach (var plcMl in li4)
                    //{
                    //    if (plcMl.DbBlockType == "Send")
                    //    {
                    //        if (plcMl.DataType == "Bit")
                    //        {
                    //            var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                    //            if (plcMl.PlcNameZH == "允许入库")
                    //            {
                    //                isIn = plcHelper.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString()));
                    //                // plcHelper.WriteBool((int)plcMl.DbBlock, (int)plcMl.Offset, true, DataType.DataBlock, biAdr);

                    //            }
                    //        }
                    //    }

                    //}
                }


                if (isMeasure == true&& eQU_TOOL_Measure.TogetherSeq>=3)
                {
                    if (true)
                    {
                        eQU_TOOL_Measure.TogetherSeq = 3;
                        List<string> arry41 = new List<string>();

                        arry41.Add("允许入库");
                        var li41 = li.Where(t => t.DbBlockType == "Send" && arry41.Contains(t.PlcNameZH)).ToList();
                        foreach (var plcMl in li41)
                        {
                            if (plcMl.DbBlockType == "Send")
                            {
                                if (plcMl.DataType == "Bit")
                                {
                                    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                                    if (plcMl.PlcNameZH == "允许入库")
                                    {
                                        isIn = plcHelper.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString()));
                                        // plcHelper.WriteBool((int)plcMl.DbBlock, (int)plcMl.Offset, true, DataType.DataBlock, biAdr);

                                    }
                                }
                            }

                        }
                    }
                    // ApplicationStatus.SetRunningState(true);
                    //读取测量结果PLC                   
                    ReadPLCMeasureData(li, eQU_Tool, eQU_Holder, plcHelper, eQU_ACCESSORY1, eQU_ACCESSORY2, eQU_ACCESSORY3);
                    //4.判断结果入库或退库
                    var isInOut = "In";
                    //判断入库还是退库
                    if (true)
                    {
                        decimal? acelenght = 0;
                        if(eQU_ACCESSORY1!=null)
                        {
                            acelenght = (eQU_ACCESSORY1.AceL == null ? 0 : eQU_ACCESSORY1.AceL);
                        }
                        if (eQU_ACCESSORY2 != null)
                        {
                            acelenght = (eQU_ACCESSORY2.AceL == null ? 0 : eQU_ACCESSORY2.AceL);
                        }
                        if (eQU_ACCESSORY3 != null)
                        {
                            acelenght = (eQU_ACCESSORY3.AceL == null ? 0 : eQU_ACCESSORY3.AceL);
                        }
                        var reality_pairing_length_Theory = eQU_Tool.knife_length + eQU_Holder.HolderLTheory + acelenght;
                        eQU_Tool.reality_pairing_length = eQU_Tool.reality_knife_length + eQU_Holder.HolderL +( eQU_Tool.Ace1L==null?0 : eQU_Tool.Ace1L);
                        eQU_TOOL_Measure.Description = "";
                        //显示
                        if ((eQU_Tool.reality_pairing_length - reality_pairing_length_Theory)  <0)
                        {
                            //isInOut = "InOut";
                            //eQU_TOOL_Measure.IsInOut = "InOut";
                            eQU_TOOL_Measure.Description+= $"总长[0,3]！实际对刀长{eQU_Tool.reality_pairing_length},理论对刀长{reality_pairing_length_Theory}";

                        }
                        else if ((eQU_Tool.reality_pairing_length - reality_pairing_length_Theory) > 3)
                        {
                            //isInOut = "InOut";
                            //eQU_TOOL_Measure.IsInOut = "InOut";
                            eQU_TOOL_Measure.Description+= $"总长[0,3]！实际对刀长{eQU_Tool.reality_pairing_length},理论对刀长{reality_pairing_length_Theory}";
                          
                        }
                        else if (Math.Abs((decimal)(eQU_Tool.reality_R - eQU_Tool.R)) > (decimal)0.1)
                        {
                            //isInOut = "InOut";
                            //eQU_TOOL_Measure.IsInOut = "InOut";
                            eQU_TOOL_Measure.Description += $"R[0.1,0.1]！实际R{eQU_Tool.reality_R},理论R{eQU_Tool.R}";
                         
                        }
                        else if ((eQU_Tool.reality_knife_length - eQU_Tool.knife_length) < 0)
                        {
                            //isInOut = "InOut";
                            //eQU_TOOL_Measure.IsInOut = "InOut";
                            eQU_TOOL_Measure.Description += $"【理论刀长{eQU_Tool.knife_length}实际刀长{eQU_Tool.reality_knife_length}";
                           
                        }
                        else if ((eQU_Tool.reality_knife_length - eQU_Tool.knife_length) >= 0)
                        {
                            //isInOut = "In";
                            //eQU_TOOL_Measure.IsInOut = "In";
                            eQU_TOOL_Measure.Description = "测量合格,请入库！";

                        }
                        else
                        {
                            //isInOut = "Out";
                            //eQU_TOOL_Measure.IsInOut = "Out";
                            eQU_TOOL_Measure.Description = $"测量不合格,请退库！【理论刀长{eQU_Tool.knife_length}实际刀长{eQU_Tool.reality_knife_length}2.理论对刀长{eQU_Tool.reality_pairing_length}实际对刀长{reality_pairing_length_Theory}】";
                           
                    
                        }
                        
                        if ((eQU_Tool.reality_pairing_length - reality_pairing_length_Theory) > 3)
                        {
                            isInOut = "InOut";
                            eQU_TOOL_Measure.IsInOut = "InOut";
                            //eQU_TOOL_Measure.Description = $"总长[0,3]！实际对刀长{eQU_Tool.reality_pairing_length},理论对刀长{reality_pairing_length_Theory}";
                            ApplicationStatus.SetRunningState(true);
                        }
                        else if ( Math.Abs((decimal)(eQU_Tool.reality_R - eQU_Tool.R) )> (decimal)0.1)
                        {
                            isInOut = "InOut";
                            eQU_TOOL_Measure.IsInOut = "InOut";
                            //eQU_TOOL_Measure.Description = $"R[0.1,0.1]！实际R{eQU_Tool.reality_R},理论R{eQU_Tool.R}";
                            ApplicationStatus.SetRunningState(true);
                        }
                        else if ((eQU_Tool.reality_knife_length - eQU_Tool.knife_length) < 0)
                        {
                            isInOut = "InOut";
                            eQU_TOOL_Measure.IsInOut = "InOut";
                            //eQU_TOOL_Measure.Description =$"【理论刀长{eQU_Tool.knife_length}实际刀长{eQU_Tool.reality_knife_length}";
                            ApplicationStatus.SetRunningState(true);
                        }
                        else if((eQU_Tool.reality_knife_length - eQU_Tool.knife_length) >=0)
                        {         
                            isInOut = "In";
                            eQU_TOOL_Measure.IsInOut = "In";
                            //eQU_TOOL_Measure.Description = "测量合格,请入库！";
                            ApplicationStatus.SetRunningState(true);
                        }
                        else
                        {
                            eQU_TOOL_Measure.IsInOut = "Out";
                            //eQU_TOOL_Measure.Description=$"测量不合格,请退库！【理论刀长{eQU_Tool.knife_length}实际刀长{eQU_Tool.reality_knife_length}2.理论对刀长{eQU_Tool.reality_pairing_length}实际对刀长{reality_pairing_length_Theory}】";
                            isInOut = "Out";
                            ApplicationStatus.SetRunningState(false);
                        }
                        eQU_TOOL_Measure.Description += $"({isInOut})";

                    }

                    

                    
                    eQU_TOOL_Measure.IsInOut = isInOut;
                    //5.入库位置或退库
                    if (isInOut == "Out"&& shelf!=null)
                    {
                        shelf.OrderCode ="";
                        shelf.RfidCode ="";
                    }
                    if (isInOut == "In")
                    {
                       
                        List<string> arry5 = new List<string>();
                        arry5.Add("放刀位置编号");
                        arry5.Add("取bt40刀");
                        arry5.Add("取A63刀");
                        arry5.Add("测量完成");
                        arry5.Add("放刀中");
                        arry5.Add("放刀完成");
                        var li5 = li3config.Where(t => arry5.Contains(t.PlcNameZH)).ToList();
                        plcHelper3.Plc = new Plc(CpuType.S71500, li5.FirstOrDefault().PlcIP, 0, 1);
                        if (plcHelper3.Plc.IsConnected)
                        { }
                        else
                        {
                            plcHelper3.Plc.Open();
                        }

                        foreach (var plcMl in li5)
                        {
                            if (plcMl.DbBlockType == "Receive")
                            {
                                if (plcMl.DataType == "Bit")
                                {
                                    if (plcMl.PlcNameZH == "测量完成" && plcHelper3.Plc.IsConnected == true)
                                    {
                                        var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                                     //   isPlayKnifeComplete = plcHelper3.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString()));
                                    }
                                    if (plcMl.PlcNameZH == "放刀中" && plcHelper3.Plc.IsConnected == true)
                                    {
                                        var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                                        isPlanyKnifeLoading = plcHelper3.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString()));
                                    }
                                    if (plcMl.PlcNameZH == "放刀完成")
                                    {
                                        var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                        isPlayKnifeComplete = plcHelper3.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString()));
                                        // 设置运行状态
                                        if(isPlayKnifeComplete==true)
                                        {
                                            ApplicationStatus.SetRunningState(false);
                                            eQU_TOOL_Measure.RfidCode="";
                                        }

                                    }
                                }
                            }
                        }
                        //分配库位点
                        var eq = eQU_Tool.HolderTypeId;
                        var count = shelvelist.OrderBy(t => t.DBCode).Where(t => t.HolderTypeId == eq && t.Status == "True" &&t.RfidCode==rfidplc).Count();
                        if (count > 0)
                        {
                            eQU_TOOL_Measure.Description =$"Rfid已占用库位{rfidplc}";
                            if (eQU_TOOL_Measure != null)
                            {

                                repository.DbContext.Set<EQU_TOOL_Measure>().Update(eQU_TOOL_Measure);
                                repository.DbContext.SaveChanges();
                            }
                            webResponse.Data = $"Rfid已占用库位！{rfidplc}";
                            return webResponse.Error($"Rfid已占用库位！{rfidplc}");
                        }
                        var count1 = shelvelist.OrderBy(t => t.DBCode).Where(t => t.HolderTypeId == eq &&(t.OrderCode != "" || t.OrderCode != null) && t.RfidCode == rfidplc).Count();
                        if (count1 > 0)
                        {
                            eQU_TOOL_Measure.Description = $"台账已分配库位{rfidplc}";
                            if (eQU_TOOL_Measure != null)
                            {

                                repository.DbContext.Set<EQU_TOOL_Measure>().Update(eQU_TOOL_Measure);
                                repository.DbContext.SaveChanges();
                            }
                            webResponse.Data = $"台账已分配库位！{rfidplc}";
                            return webResponse.Error($"台账已分配库位！{rfidplc}");
                        }
                        shelf = shelvelist.OrderBy(t=>t.DBCode).Where(t => t.HolderTypeId == eq && t.Status == "True").FirstOrDefault();
                        if (shelf != null)
                        {
                            location = shelf.DBCode.Value;
                            eQU_TOOL_Measure.location= location;
                            shelf.OrderCode = eQU_Tool.Identifier;
                            shelf.RfidCode = eQU_Tool.RfidCode;
                        }
                        else
                        {
                            eQU_TOOL_Measure.Description += "没有找到货架库位位置！";
                            if (eQU_TOOL_Measure != null)
                            {

                                repository.DbContext.Set<EQU_TOOL_Measure>().Update(eQU_TOOL_Measure);
                                repository.DbContext.SaveChanges();
                            }
                            webResponse.Data = $"没有找到货架库位位置！{rfidplc}";
                                return webResponse.Error($"没有找到货架库位位置！{rfidplc}");
                            
                           
                        }
                        Thread.Sleep(100);
                        if (isPlanyKnifeLoading == false)
                        {
                            foreach (var plcMl in li5)
                            {
                                if (plcMl.DbBlockType == "Send")
                                {
                                    if (plcMl.DataType == "Word")
                                    {
                                        if (plcMl.PlcNameZH == "放刀位置编号")
                                        {
                                            eQU_Tool.RfidCode = rfidplc;
                                            plcMl.CurrentWriteValue = location.ToString(); //"30";
                                            eQU_Tool.location = location;
                                            if (shelf !=null)
                                            {
                                                eQU_Tool.SHELVES_Id = shelf == null ? null : shelf.INTE_SHELVES_Id.ToString().ToUpper();
                                                shelf.ToolId = eQU_Tool.Id.ToString().ToUpper();
                                            }
                                            
                                            plcHelper3.WriteWord((int)plcMl.DbBlock, (int)plcMl.Offset, ushort.Parse(location.ToString()));
                                        }
                                    }
                                }
                            }
                            //通知plc取那类刀
                            //  Thread.Sleep(3000);
                            foreach (var plcMl in li5)
                            {
                                if (plcMl.DbBlockType == "Send")
                                {

                                    if (plcMl.DataType == "Bit")
                                    {//HolderTypeId
                                        var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                        if (plcMl.PlcNameZH == "取bt40刀" && eQU_Tool.HolderTypeId == "BT40")
                                        {
                                            plcHelper3.WriteBool((int)plcMl.DbBlock, (int)plcMl.Offset, true, DataType.DataBlock, biAdr);
                                        }
                                        else if (plcMl.PlcNameZH == "取A63刀" && eQU_Tool.HolderTypeId == "A63")
                                        {
                                            plcHelper3.WriteBool((int)plcMl.DbBlock, (int)plcMl.Offset, true, DataType.DataBlock, biAdr);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    //6.发送入库或退库
                    List<string> arry4 = new List<string>();
                    arry4.Add("请求退库");
                    arry4.Add("允许入库");
                    var li4 = li.Where(t => t.DbBlockType == "Send" && arry4.Contains(t.PlcNameZH)).ToList();
                    foreach (var plcMl in li4)
                    {
                        if (plcMl.DbBlockType == "Send")
                        {
                            if (plcMl.DataType == "Bit")
                            {
                                var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                if (plcMl.PlcNameZH == "请求退库" && isInOut == "Out")
                                {
                                    plcHelper.WriteBool((int)plcMl.DbBlock, (int)plcMl.Offset, true, DataType.DataBlock, biAdr);
                                    isInOut = "Out";
                                }
                                if (plcMl.PlcNameZH == "允许入库" && isInOut == "In")
                                {
                                    plcHelper.WriteBool((int)plcMl.DbBlock, (int)plcMl.Offset, true, DataType.DataBlock, biAdr);
                                    isInOut = "In";
                                    eQU_TOOL_Measure.IsInOut = "auto";
                                    eQU_TOOL_Measure.Description = "允许自动入库！";

                                }
                            }
                        }

                    }
                }
                
                if (eQU_TOOL_Measure != null)
                {
                    eQU_TOOL_Measure.Identifier = eQU_Tool.Identifier;
                    eQU_TOOL_Measure.tool_name = eQU_Tool.tool_name;
                    eQU_TOOL_Measure.program_seq = eQU_Tool.program_seq;
                
                    eQU_TOOL_Measure.location = eQU_Tool.location;
                    eQU_TOOL_Measure.Holder_Code= eQU_Tool.Holder_Code;
                    eQU_TOOL_Measure.HolderL= eQU_Tool.HolderL;
                    eQU_TOOL_Measure.reality_knife_width = eQU_Tool.reality_knife_width;
                    eQU_TOOL_Measure.knife_width = eQU_Tool.knife_width;

                    eQU_TOOL_Measure.Accessorie1Code = eQU_Tool.Accessorie1Code;
                    eQU_TOOL_Measure.Accessorie2Code = eQU_Tool.Accessorie2Code;
                    eQU_TOOL_Measure.Accessorie3_Code = eQU_Tool.Accessorie3_Code;
                    eQU_TOOL_Measure.handle_type = eQU_Tool.handle_type;

                    eQU_TOOL_Measure.reality_knife_width = eQU_Tool.reality_knife_width;
                    eQU_TOOL_Measure.knife_width = eQU_Tool.knife_width;
                    eQU_TOOL_Measure.knife_length = eQU_Tool.knife_length;
                    eQU_TOOL_Measure.reality_knife_length = eQU_Tool.reality_knife_length;
                    if (eQU_Holder != null)
                    {
                        eQU_TOOL_Measure.HolderLTheory = eQU_Holder.HolderLTheory;
                    }
                    eQU_TOOL_Measure.HolderBDTheory = eQU_Tool.HolderBDTheory;
                    eQU_TOOL_Measure.HolderL = eQU_Tool.HolderL;
                    eQU_TOOL_Measure.vendor_code = eQU_Tool.Id.ToString();
                    eQU_TOOL_Measure.HolderBD = eQU_Tool.HolderBD;
                    eQU_TOOL_Measure.Ace1LTheory = eQU_Tool.Ace1LTheory;
                    eQU_TOOL_Measure.Ace1L = eQU_Tool.Ace1L;
                }
                if(isPlayKnifeComplete==true)
                {
                    await _hubContext.Clients.All.SendAsync("ShowMsg1", new MsgInfo { Title = ":", MsgContent = $"放刀完成！" });
                }
                WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
                {
                    if(eQU_ACCESSORY1!=null)
                    {
                        repository.DbContext.Set<EQU_ACCESSORY>().Update(eQU_ACCESSORY1);
                        repository.DbContext.SaveChanges();
                    }
                    if (eQU_ACCESSORY2 != null)
                    {
                        repository.DbContext.Set<EQU_ACCESSORY>().Update(eQU_ACCESSORY2);
                        repository.DbContext.SaveChanges();
                    }
                    if (eQU_ACCESSORY3 != null)
                    {
                        repository.DbContext.Set<EQU_ACCESSORY>().Update(eQU_ACCESSORY3);
                        repository.DbContext.SaveChanges();
                    }
                    if (eQU_Holder!=null)
                    {
                        repository.DbContext.Set<EQU_Holder>().Update(eQU_Holder);
                        repository.DbContext.SaveChanges();
                    }
                    if (eQU_Tool != null)
                    {
                       
                        repository.DbContext.Set<EQU_TOOL>().Update(eQU_Tool);
                        repository.DbContext.SaveChanges();
                    }
                    var eq = eQU_Tool.HolderTypeId;
                    shelf = shelvelist.OrderBy(t => t.DBCode).Where(t => t.HolderTypeId == eq && t.DBCode == eQU_TOOL_Measure.location).FirstOrDefault();
                    if (shelf != null && isPlayKnifeComplete == true)
                    {
                       
                        //  eQU_TOOL_Measure.location = location;
                        shelf.OrderCode = eQU_Tool.Identifier;
                        shelf.RfidCode = eQU_Tool.RfidCode;                        
                        repository.DbContext.Set<INTE_SHELVES>().Update(shelf);
                        repository.DbContext.SaveChanges();
                    }
                    if ( isPlayKnifeComplete == true)
                    {
                        if (true)
                        {
                            List<string> arry6 = new List<string>();
                            arry6.Add("放刀完成");
                            var li5 = li3config.Where(t => arry6.Contains(t.PlcNameZH)).ToList();
                            plcHelper3.Plc = new Plc(CpuType.S71500, li5.FirstOrDefault().PlcIP, 0, 1);
                            if (plcHelper3.Plc.IsConnected)
                            { }
                            else
                            {
                                plcHelper3.Plc.Open();
                            }

                            foreach (var plcMl in li5)
                            {
                                if (plcMl.DbBlockType == "Receive")
                                {
                                    if (plcMl.DataType == "Bit")
                                    {
                                        if (plcMl.PlcNameZH == "放刀完成")
                                        {
                                            var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                            plcHelper3.WriteBool((int)plcMl.DbBlock, (int)plcMl.Offset, false, DataType.DataBlock, biAdr);
                                            eQU_TOOL_Measure.IsInOut = "End";
                                            eQU_TOOL_Measure.Description = "入库完成！";

                                        }
                                    }
                                }
                            }
                            plcHelper3.ClosePlc(plcHelper3.Plc);

                        }
                   
                    }
                    if (eQU_TOOL_Measure!=null)
                    {
                        
                        repository.DbContext.Set<EQU_TOOL_Measure>().Update(eQU_TOOL_Measure);
                        repository.DbContext.SaveChanges();
                    }
                    //else
                    //{
                    //    eQU_TOOL_Measure = new EQU_TOOL_Measure();
                    //    eQU_TOOL_Measure.Identifier = eQU_Tool.Identifier;
                    //    eQU_TOOL_Measure.tool_name = eQU_Tool.tool_name;
                    //    eQU_TOOL_Measure.program_seq = eQU_Tool.program_seq;
                    //    if(eQU_TOOL_Measure.IsInOut =="Out")//退库
                    //    { 
                    //        eQU_TOOL_Measure.RfidCode = "";
                    //        eQU_TOOL_Measure.TogetherSeq = -1;
                    //    }
                    //    //else//入库
                    //    //{ eQU_TOOL_Measure.RfidCode =""; }
                        
                    //    eQU_TOOL_Measure.Holder_Code = eQU_Tool.Holder_Code;
                    //    eQU_TOOL_Measure.HolderL = eQU_Tool.HolderL;
                    //    eQU_TOOL_Measure.Identifier=eQU_Tool.Identifier;
                    //    eQU_TOOL_Measure.R=eQU_Tool.R;
                    //    eQU_TOOL_Measure.reality_knife_length = eQU_Tool.reality_knife_length;
                    //    eQU_TOOL_Measure.reality_pairing_length = eQU_Tool.reality_pairing_length;
                    //    eQU_TOOL_Measure.location = eQU_Tool.location;
                    //    repository.DbContext.Set<EQU_TOOL_Measure>().Add(eQU_TOOL_Measure);
                    //    repository.DbContext.SaveChanges();

                    //}
                    return webResponse.OK(ResponseType.Success);
                });
                Logger.Info(LoggerType.Success, eQU_Tool.Serialize(), webResponse.Message, msg);
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                Logger.Info(LoggerType.Exception, eQU_Tool.Serialize(), webResponse.Message, msg);
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {
                plcHelper.ClosePlc(plcHelper.Plc);
                plcHelper3.ClosePlc(plcHelper3.Plc);
                //AtomicStatus.Stop();
            }
        }
        /// <summary>
        /// 从PLC读取测量结果
        /// </summary>
        /// <param name="li"></param>
        /// <param name="eQU_Tool"></param>
        /// <param name="eQU_Holder"></param>
        /// <param name="plcHelper"></param>
        private static void ReadPLCMeasureData(List<EQU_PLCConfig> li, EQU_TOOL eQU_Tool, EQU_Holder eQU_Holder, PlcHelper plcHelper,EQU_ACCESSORY eQU_ACCESSORY1, EQU_ACCESSORY eQU_ACCESSORY2, EQU_ACCESSORY eQU_ACCESSORY3)
        {
            foreach (var plcMl in li)
            {
                if (plcMl.DbBlockType == "Receive")
                {
                    if (plcMl.DataType == "Real")
                    {
                        if (plcMl.PlcNameZH == "刀具R角")
                        {//2147483647
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                            if(plcMl.CurrentValue== "2.1474836E+09")
                            {
                                eQU_Tool.reality_R = 2147;
                            }
                            else
                            {
                                eQU_Tool.reality_R = decimal.Parse(plcMl.CurrentValue);
                            }
                            
                        }
                        if (plcMl.PlcNameZH == "刀具直径")
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                            if (plcMl.CurrentValue == "2.1474836E+09")
                            {
                                eQU_Tool.reality_knife_width = 2147;
                            }
                            else
                            {
                                eQU_Tool.reality_knife_width = decimal.Parse(plcMl.CurrentValue);
                            }
                            
                        }
                        if (plcMl.PlcNameZH == "刀具和中心线误差")
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                        }
                        if (plcMl.PlcNameZH == "刀具和中心线误差2")
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                        }
                        if (plcMl.PlcNameZH == "刀具电机 当前位置")
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                        }
                        if (plcMl.PlcNameZH == "刀柄半径")
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                            if (plcMl.CurrentValue == "2.1474836E+09")
                            {
                                eQU_Holder.HolderBD = 2147;
                                eQU_Tool.HolderBD = 2147;
                            }
                            else
                            {
                                if (eQU_Holder != null)
                                {
                                    eQU_Holder.HolderBD = decimal.Parse(plcMl.CurrentValue);
                                    eQU_Tool.HolderBD = decimal.Parse(plcMl.CurrentValue);
                                }
                            }
                            

                        }
                        if (plcMl.PlcNameZH == "刀柄长")
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                            if (eQU_Holder != null)
                            {
                                eQU_Holder.HolderL = decimal.Parse(plcMl.CurrentValue);
                                eQU_Tool.HolderL = decimal.Parse(plcMl.CurrentValue);
                            }

                        }
                        if (plcMl.PlcNameZH == "刀柄和中心线误差1")
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                        }
                        if (plcMl.PlcNameZH == "刀柄和中心线误差2")
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                        }
                        if (plcMl.PlcNameZH == "刀柄电机当前位置")
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                        }
                        if (plcMl.PlcNameZH == "加长杆1直径")
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                        }
                        if (plcMl.PlcNameZH == "加长杆1和中心线误差1")
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                        }
                        if (plcMl.PlcNameZH == "加长杆1和中心线误差2")
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                        }
                        if (plcMl.PlcNameZH == "加长杆1电机当前位置")
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                        }
                        if (plcMl.PlcNameZH == "加长杆2直径")
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                        }
                        if (plcMl.PlcNameZH == "加长杆2和中心线误差1")
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                        }
                        if (plcMl.PlcNameZH == "加长杆2和中心线误差2")
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                        }
                        if (plcMl.PlcNameZH == "加长杆2电机当前位置")
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                        }
                        if (plcMl.PlcNameZH == "加长杆3直径")
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                        }
                        if (plcMl.PlcNameZH == "加长杆3和中心线误差1")
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                        }
                        if (plcMl.PlcNameZH == "加长杆3和中心线误差2")
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                        }
                        if (plcMl.PlcNameZH == "加长杆3和电机当前位置")
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                        }
                        if (plcMl.PlcNameZH == "刀具实际长度")
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                            eQU_Tool.reality_knife_length = decimal.Parse(plcMl.CurrentValue);
                           //decimal.Parse(plcMl.CurrentValue);
                        }
                        if (plcMl.PlcNameZH == "刀柄实际长度")
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                        }
                        if (plcMl.PlcNameZH == "加长杆1实际长度" && eQU_ACCESSORY1 != null)
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                            eQU_Tool.Ace1LTheory = eQU_ACCESSORY1.AceL;
                            eQU_Tool.Ace1L = decimal.Parse(plcMl.CurrentValue);
                        }
                        if (plcMl.PlcNameZH == "加长杆2实际长度" && eQU_ACCESSORY2 != null)
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                            eQU_Tool.Ace2LTheory = eQU_ACCESSORY2.AceL;
                            eQU_Tool.Ace2L = decimal.Parse(plcMl.CurrentValue);
                        }
                        if (plcMl.PlcNameZH == "加长杆3实际长度" && eQU_ACCESSORY3 != null)
                        {
                            plcMl.CurrentValue = plcHelper.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                            eQU_Tool.Ace3LTheory = eQU_ACCESSORY3.AceL;
                            eQU_Tool.Ace3L = decimal.Parse(plcMl.CurrentValue);
                           // eQU_ACCESSORY3.l
                        }

                    }

                }

            }
            //var reality_pairing_length_Theory = eQU_Tool.knife_length + eQU_Holder.HolderLTheory + eQU_Tool.HolderLTheory;
            eQU_Tool.reality_pairing_length = eQU_Tool.reality_knife_length + eQU_Holder.HolderL+(eQU_Tool.Ace1L==null?0: eQU_Tool.Ace1L);   
        }

        /// <summary>
        /// 开始测量 发送数据MES给PLC
        /// </summary>
        /// <param name="li"></param>
        /// <param name="eQU_Tool"></param>
        /// <param name="eQU_Holder"></param>
        /// <param name="eQU_ACCESSORY1"></param>
        /// <param name="eQU_ACCESSORY2"></param>
        /// <param name="eQU_ACCESSORY3"></param>
        /// <param name="plc"></param>
        /// <param name="rfidplc"></param>
        /// <param name="list"></param>
        private void StartCheckSendData(List<EQU_PLCConfig> li, EQU_TOOL eQU_Tool, EQU_ToolModel eQU_ToolModel,  EQU_Holder eQU_Holder, EQU_ACCESSORY eQU_ACCESSORY1, EQU_ACCESSORY eQU_ACCESSORY2, EQU_ACCESSORY eQU_ACCESSORY3, Plc plc, string rfidplc, List<EQU_PLCConfig> list,out string outmes)
        {
            outmes= "";
            List<string> arry = new List<string>();
            arry.Add("刀具模板号");
            arry.Add("刀柄模板号");
            arry.Add("加长西杆1模板号");
            arry.Add("加长杆2模板号");
            arry.Add("加长杆3模板号");
            arry.Add("刀长");
            arry.Add("刀柄长");
            arry.Add("加长杆长1");
            arry.Add("加长杆长2");
            arry.Add("加长杆长3");
            var licheck = list.Where(t => t.DbBlockType == "Send" && arry.Contains(t.PlcNameZH)).ToList();

            foreach (var plcMl in licheck)
            {

                if (plcMl.DbBlockType == "Send")
                {

                    if (plcMl.DataType == "Word")
                    {

                        if (plcMl.PlcNameZH == "刀具模板号")
                        {
                            var rfid = eQU_ToolModel != null ? eQU_ToolModel.MeasureTemplate : eQU_Tool.MeasureTemplate;//eQU_TOOL.RfidCode;
                          //  plcHelper3.WriteWord((int)plcMl.DbBlock, (int)plcMl.Offset, ushort.Parse(location.ToString()));                                                                                          //   PlcHelper.Instance.WriteDWord((int)plcMl.DbBlock, (int)plcMl.Offset, uint.Parse(rfid));
                            if(rfid==null)
                            {
                                outmes = "刀具模板号不能为空！";
                                return;
                            }
                            plc.Write(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, ushort.Parse(rfid));
                            Thread.Sleep(200); // 模拟工作
                        }
                        if (plcMl.PlcNameZH == "刀柄模板号")
                        {
                            var rfid = eQU_Holder != null ? eQU_Holder.MeasureTemplate : "";//eQU_TOOL.RfidCode;
                                                                                         //   PlcHelper.Instance.WriteDWord((int)plcMl.DbBlock, (int)plcMl.Offset, uint.Parse(rfid));
                            if(rfid == null)
                            {
                                outmes = "刀柄模板号不能为空！";
                                return;
                            }
                            plc.Write(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, ushort.Parse(rfid));
                            Thread.Sleep(200); // 模拟工作
                        }
                        if (plcMl.PlcNameZH == "加长西杆1模板号")
                        {
                            var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                            //   PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(eQU_ACCESSORY1.MeasureTemplate));
                            if (plc.IsConnected == true && eQU_ACCESSORY1 != null)
                            {
                                var rfid = eQU_ACCESSORY1.MeasureTemplate;
                                if(rfid == null)
                                {
                                    outmes = "加长西杆1模板号不能为空！";
                                    return;
                                }
                                plc.Write(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, ushort.Parse(rfid));
                                
                                Thread.Sleep(200); // 模拟工作
                            }
                            // plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                        }
                        if (plcMl.PlcNameZH == "加长杆2模板号")
                        {

                            var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                            if (plc.IsConnected == true && eQU_ACCESSORY2 != null)
                            {
                                //PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(eQU_ACCESSORY2.MeasureTemplate));
                                var rfid = eQU_ACCESSORY2.MeasureTemplate;
                                if(rfid == null)
                                {
                                    outmes = "加长杆2模板号不能为空！";
                                    return;
                                }
                                plc.Write(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, ushort.Parse(rfid));
                                Thread.Sleep(200); // 模拟工作
                            }
                            // plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                        }
                        if (plcMl.PlcNameZH == "加长杆3模板号")
                        {

                            var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                            if (plc.IsConnected == true && eQU_ACCESSORY3 != null)
                            {
                                var rfid = eQU_ACCESSORY3.MeasureTemplate;
                                if(rfid == null)
                                {
                                    outmes = "加长杆3模板号不能为空！";
                                    return;
                                }
                                plc.Write(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, ushort.Parse(rfid));
                                Thread.Sleep(200); // 模拟工作
                            }
                            // PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(eQU_ACCESSORY3.MeasureTemplate));
                            // plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                        }

                    }
                    //if (plcMl.DataType == "Byte")
                    //{

                    //    if (plcMl.PlcNameZH == "刀具模板号")
                    //    {
                    //        var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);


                    //        if (plc.IsConnected == true && eQU_Tool != null)
                    //        {
                    //            var bytenew = eQU_ToolModel!=null? byte.Parse( eQU_ToolModel.MeasureTemplate): byte.Parse(eQU_Tool.MeasureTemplate);//  byte.Parse(biAdr.ToString());

                    //            plc.WriteBytes(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, new byte[] { bytenew });
                    //            Thread.Sleep(200); // 模拟工作
                    //        }

                    //        //  plc.WriteBytes(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, new byte[] { bytenew });
                    //        //  PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(eQU_EQUIPMENT.MeasureTemplate),(S7.Net.DataType)biAdr);
                    //        //   plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                    //    }

                    //    if (plcMl.PlcNameZH == "刀柄模板号")
                    //    {
                    //        var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                    //        //    PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, new byte[] { bytenew });
                    //        if (plc.IsConnected == true && eQU_Holder != null)
                    //        {
                    //            var bytenew = byte.Parse(eQU_Holder.MeasureTemplate);
                    //            plc.WriteBytes(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, new byte[] { bytenew });
                    //            Thread.Sleep(200); // 模拟工作
                    //        }
                    //        //  plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                    //    }
                    //    if (plcMl.PlcNameZH == "加长西杆1模板号")
                    //    {
                    //        var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                    //        //   PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(eQU_ACCESSORY1.MeasureTemplate));
                    //        if (plc.IsConnected == true && eQU_ACCESSORY1 != null)
                    //        {
                    //            var bytenew = byte.Parse(eQU_ACCESSORY1.MeasureTemplate);

                    //            plc.WriteBytes(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, new byte[] { bytenew });
                    //            Thread.Sleep(200); // 模拟工作
                    //        }
                    //        // plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                    //    }
                    //    if (plcMl.PlcNameZH == "加长杆2模板号")
                    //    {

                    //        var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                    //        if (plc.IsConnected == true && eQU_ACCESSORY2 != null)
                    //        {
                    //            //PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(eQU_ACCESSORY2.MeasureTemplate));
                    //            var bytenew = byte.Parse(eQU_ACCESSORY2.MeasureTemplate);

                    //            plc.WriteBytes(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, new byte[] { bytenew });
                    //            Thread.Sleep(200); // 模拟工作
                    //        }
                    //        // plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                    //    }
                    //    if (plcMl.PlcNameZH == "加长杆3模板号")
                    //    {

                    //        var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                    //        if (plc.IsConnected == true && eQU_ACCESSORY3 != null)
                    //        {
                    //            var bytenew = byte.Parse(eQU_ACCESSORY3.MeasureTemplate);

                    //            plc.WriteBytes(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, new byte[] { bytenew });
                    //            Thread.Sleep(200); // 模拟工作
                    //        }
                    //        // PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(eQU_ACCESSORY3.MeasureTemplate));
                    //        // plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                    //    }

                    //}

                    if (plcMl.PlcNameZH == "刀长" && eQU_Tool != null)
                    {
                        // PlcHelper.Instance.WriteReal((int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(plcMl.CurrentWriteValue));

                        //    PlcHelper.Instance.WriteReal((int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_EQUIPMENT.knife_length.ToString()));
                        if (plc.IsConnected == true)
                        {

                            plc.Write(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_Tool.knife_length.ToString()));
                            Thread.Sleep(200); // 模拟工作
                        }
                    }
                    if (plcMl.PlcNameZH == "刀柄长" && eQU_Holder != null)
                    {
                        //PlcHelper.Instance.WriteReal((int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_Holder.HolderL.ToString()));
                        if (plc.IsConnected == true)
                        {
                            plc.Write(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_Holder.HolderLTheory.ToString()));
                            Thread.Sleep(200); // 模拟工作
                        }
                    }
                    if (plcMl.PlcNameZH == "加长杆长1" && eQU_ACCESSORY1 != null)
                    {
                        //PlcHelper.Instance.WriteReal((int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_ACCESSORY1.AceL.ToString()));
                        if (plc.IsConnected == true)
                        {

                            plc.Write(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_ACCESSORY1.AceL.ToString()));
                            Thread.Sleep(200); // 模拟工作
                        }
                    }
                    if (plcMl.PlcNameZH == "加长杆长2" && eQU_ACCESSORY2 != null)
                    {
                        // PlcHelper.Instance.WriteReal((int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_ACCESSORY2.AceL.ToString()));
                        if (plc.IsConnected == true)
                        {

                            plc.Write(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_ACCESSORY2.AceL.ToString()));
                            Thread.Sleep(200); // 模拟工作
                        }
                    }
                    if (plcMl.PlcNameZH == "加长杆长3" && eQU_ACCESSORY3 != null)
                    {
                        // PlcHelper.Instance.WriteReal((int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_ACCESSORY3.AceL.ToString()));
                        if (plc.IsConnected == true)
                        {

                            plc.Write(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(eQU_ACCESSORY3.AceL.ToString()));
                            Thread.Sleep(200); // 模拟工作
                        }
                    }


                    //repository.DbContext.Set<EQU_PLCConfig>().Update(plcMl);
                    //repository.SaveChanges();
                }

            }
            List<string> arry2 = new List<string>();
            arry2.Add("开始启动");
            arry2.Add("RFIDMES到PLC");
            var li2 = li.Where(t => t.DbBlockType == "Send" && arry2.Contains(t.PlcNameZH)).ToList();

            foreach (var plcMl in li2)
            {

                if (plcMl.DbBlockType == "Send")
                {
                    if (plcMl.DataType == "Bit")
                    {
                        var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                        if (plcMl.PlcNameZH == "开始启动")
                        {
                            plc.WriteBit(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, biAdr, true);

                            Thread.Sleep(200); // 模拟工作
                        }
                        //  plcMl.CurrentValue = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                    }
                    if (plcMl.DataType == "DWord")
                    {
                        if (plcMl.PlcNameZH == "RFIDMES到PLC")
                        {
                            var rfid = rfidplc;//eQU_TOOL.RfidCode;
                                               //   PlcHelper.Instance.WriteDWord((int)plcMl.DbBlock, (int)plcMl.Offset, uint.Parse(rfid));
                            plc.Write(DataType.DataBlock, (int)plcMl.DbBlock, (int)plcMl.Offset, uint.Parse(rfid));
                            Thread.Sleep(200); // 模拟工作
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 1.检查测量准备就绪
        /// </summary>
        /// <param name="li"></param>
        /// <param name="plcHelper"></param>
        /// <param name="startCheck"></param>
        /// <param name="rfidplc"></param>
        /// <param name="isMeasure"></param>
        /// <param name="list"></param>
        private void checkReadyMeasure(EQU_TOOL_Measure eQU_TOOL_Measure,List<EQU_PLCConfig> li, PlcHelper plcHelper, ref bool startCheck, ref string rfidplc, out bool isMeasure, out List<EQU_PLCConfig> list)
        {
            isMeasure = false;
            list = li.ToList();
            List<string> arry1 = new List<string>();
            arry1.Add("开始测量信号");
            arry1.Add("测量完成");
            arry1.Add("RFID");
            arry1.Add("对刀仪是否允许写RFID");
            arry1.Add("对刀仪使能就绪");
            arry1.Add("对刀仪异常编码");

            var licheck1 = list.Where(t => t.DbBlockType == "Receive" && arry1.Contains(t.PlcNameZH)).ToList();
            foreach (var plcMl in licheck1)
            {
                if (plcMl.DbBlockType == "Receive")
                {
                    if (plcMl.DataType == "DWord")
                    {
                        if (plcMl.PlcNameZH == "RFID" && plcHelper.Plc.IsConnected == true)
                        {
                            rfidplc = plcHelper.ReadDWord((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock).ToString();

                        }
                    }
                    if (plcMl.DataType == "Word")
                    {
                        if (plcMl.PlcNameZH == "对刀仪异常编码")
                        {
                            eQU_TOOL_Measure.FaultNoMeasure = plcHelper.ReadWord((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock).ToString();
                            //plcHelper.redw((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock).ToString();
                            // plcHelper.Instance.ReadWord((int)plcMl.DbBlock, (int)plcMl.Offset).ToString();
                        }
                    }
                    if (plcMl.DataType == "Bit")
                    {
                        if (plcMl.PlcNameZH == "开始测量信号" && plcHelper.Plc.IsConnected == true)
                        {
                            var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                            startCheck = plcHelper.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString()));

                        }
                        if (plcMl.PlcNameZH == "测量完成" && plcHelper.Plc.IsConnected == true)
                        {
                            var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                            isMeasure = plcHelper.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString()));
                        }
                        if (plcMl.PlcNameZH == "对刀仪是否允许写RFID")
                        {
                            var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                            var isWriteRfid = plcHelper.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString()));
                            eQU_TOOL_Measure.IsWriteRfid = isWriteRfid.ToString();//plcHelper.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString()));
                        }
                        if (plcMl.PlcNameZH == "对刀仪使能就绪")
                        {
                            var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                            //eQU_TOOL_Measure.IsUse = plcHelper.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString()));
                            var isUse = plcHelper.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString()));
                            eQU_TOOL_Measure.IsUse = isUse.ToString();
                        }
                    }

                }
            }
        }
        /// <summary>
        /// 推棒  192.168.1.3执行
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<WebResponseContent> PushCart()
        {
            //var inteconfig = QueryInteConfigure("EquMeasureAuto");
            //if (inteconfig == null)
            //{
            //    webResponse.Data = $"测量仪配置没有开启！";
            //    return webResponse.Error($"测量仪配置没有开启！");
            //}

            string msg = string.Empty;
            var li3config = await repository.FindAsync<EQU_PLCConfig>(t => t.PlcIP == "192.168.1.3");

            List<string> arry5 = new List<string>();
            arry5.Add("测量数值已发送");
            arry5.Add("Mes推棒百分比已发送");
            arry5.Add("推棒百分比");
            arry5.Add("A点坐标Y");
            arry5.Add("B点坐标Y");
            arry5.Add("推棒第一次");
            arry5.Add("推棒第一次Send");
            var li = li3config.Where(t => arry5.Contains(t.PlcNameZH)).ToList();
            PlcHelper plcHelper3 = new PlcHelper();
            EQU_COM_DEFINITION_TASK_RECORD eQU_COM_DEFINITION_TASK_RECORD = new EQU_COM_DEFINITION_TASK_RECORD();
            try
            {
                var plcMStart = li.Where(t => t.PlcNameZH == "测量数值已发送").FirstOrDefault();// section["Ip"];
                if (plcMStart != null)
                {
                    var ip = string.Empty;

                    if (plcMStart != null)
                    {
                        ip = plcMStart.PlcIP;
                        var isConnect = IsIpConnect(ip);
                        if (!isConnect)
                        {
                            webResponse.Data = $"{ip}连接不上！";
                            return webResponse.Error($"{ip}连接不上！");
                        }
                    }
                    plcHelper3.Plc = new Plc(CpuType.S71500, ip, 0, 1);
                    if (plcHelper3.Plc.IsConnected)
                    { }
                    else
                    {
                        plcHelper3.Plc.Open();
                    }
                    var isPlcSendNumber = false;
                    float? fristPush = 0;
                    foreach (var plcMl in li)
                    {
                        if (plcMl.DbBlockType == "Receive")
                        {
                            if (plcMl.DataType == "Bit")
                            {
                                if (plcMl.PlcNameZH == "测量数值已发送")
                                {
                                    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                    isPlcSendNumber = plcHelper3.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString()));

                                }

                            }
                            if (plcMl.DataType == "Real")
                            {
                                if (plcMl.PlcNameZH == "推棒第一次")
                                {
                                    fristPush = float.Parse(plcHelper3.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());

                                }

                            }
                        }
                    }
                    // isPlcSendNumber = true;
                    List<INTE_FIRSTCOEFFICIENT> iNTE_FIRSTCOEFFICIENTs = new List<INTE_FIRSTCOEFFICIENT>();
                    List<EQU_COM_DEFINITION_TASK_RECORD> lastMany = new List<EQU_COM_DEFINITION_TASK_RECORD>();
                    EQU_COM_DEFINITION_TASK_RECORD last = null;
                    iNTE_FIRSTCOEFFICIENTs = repository.DbContext.Set<INTE_FIRSTCOEFFICIENT>().ToList();
                    if (isPlcSendNumber == true)
                    {
                        //上条记录
                        if (fristPush == 1)
                        {
                            last = null;
                        }
                        else
                        {
                            last = repository.DbContext.Set<EQU_COM_DEFINITION_TASK_RECORD>().Where(t => t.CreateBy == "PushCart").OrderByDescending(t => t.CreateOn).FirstOrDefault();
                        }

                        if (last != null)
                        {
                            lastMany = repository.DbContext.Set<EQU_COM_DEFINITION_TASK_RECORD>().Where(t => t.CreateBy == "PushCart" && t.Description == last.Description).OrderByDescending(t => t.CreateOn).ToList();
                        }

                        foreach (var plcMl in li)
                        {
                            if (plcMl.DbBlockType == "Receive")
                            {

                                if (plcMl.DataType == "Real")
                                {

                                    if (plcMl.PlcNameZH == "B点坐标Y")
                                    {

                                        eQU_COM_DEFINITION_TASK_RECORD.BY = float.Parse(plcHelper3.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                    }
                                    if (plcMl.PlcNameZH == "A点坐标Y")
                                    {
                                        eQU_COM_DEFINITION_TASK_RECORD.AY = float.Parse(plcHelper3.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                    }
                                }
                            }
                        }

                        float? pushPercentage = 1;//推棒百分比
                        var inteconfig = QueryInteConfigure("PushRatio");
                        var ratioList = new List<string>();
                        //  var equsTaskLock = userService.QueryInteConfigure("FaultMessage");
                        if (inteconfig == null)
                        {

                        }
                        {
                            ratioList = inteconfig.ConfigureParam.Split(",").ToList();
                        }
                        var ration = (float)1;
                        float basiRation = 1;
                        float basiRation2 = 0;
                        //当前正在测量
                        var loadingtask = repository.DbContext.Set<EQU_COM_DEFINITION_TASK>().Where(t => t.Status == "2" && t.Command == "TW0032").OrderByDescending(t => t.CreateOn).FirstOrDefault();
                        var fIRSTCOEFFICIENTs = repository.DbContext.Set<INTE_FIRSTCOEFFICIENT>().ToList();
                        if (loadingtask != null)
                        {
                            var order = repository.DbContext.Set<PLAN_WORK_ORDER>().Where(t => t.OrderCode == loadingtask.OrderCode).OrderByDescending(t => t.CreateOn).FirstOrDefault();
                            if (order != null)
                            {
                                var oneequ = repository.DbContext.Set<EQU_EQUIPMENT>().Where(t => t.Description == order.processing_machines).FirstOrDefault();
                                if (oneequ != null)
                                {
                                    var one = fIRSTCOEFFICIENTs.Where(t => t.CoefficientType == oneequ.Id.ToString().ToUpper() && t.MinWeight <= float.Parse(order.ProcessWeight.ToString()) && float.Parse(order.ProcessWeight.ToString()) <= t.MaxWeight).FirstOrDefault();
                                    if (one != null)
                                    {
                                        basiRation2 = float.Parse(one.PushRatio.ToString());
                                    }
                                }

                            }
                        }
                        basiRation = basiRation2 != 0 ? basiRation2 : float.Parse(ratioList[1 - 1]);
                        if (last == null)
                        {
                            //--第一次

                            ration = basiRation * float.Parse(ratioList[2 - 1]);
                            pushPercentage = (float)1 * ration;
                        }
                        else
                        {
                            // --第一次
                            //--1 上一次绝对值A > B 推A && 当前绝对值A > B   推的百分比为1
                            //--2 上一次绝对值A > B 推A && 当前绝对值A < B   推的百分比为0.5
                            //--3 上一次绝对值A < B 推A && 当前绝对值A > B   推的百分比为0.5
                            //--4 上一次绝对值A < B 推A && 当前绝对值A < B   推的百分比为1

                            //--第二次
                            //--1 上一次绝对值A > B 推A && 当前绝对值A > B   推的百分比为1 如果上一次百分比为1 ，推的百分比为1  ，如果上一次百分比为0.5 推的百分比为0.5
                            //--2 上一次绝对值A > B 推A && 当前绝对值A < B   推的百分比为0.5   如果上一次百分比为1 ，推的百分比为0.5  ，如果上一次百分比为0.5 推的百分比为0.25

                            //--3 上一次绝对值A < B 推A && 当前绝对值A < B   推的百分比为0.5  如果上一次百分比为1 ，推的百分比为1  ，如果上一次百分比为0.5 推的百分比为0.5
                            //--4 上一次绝对值A < B 推A && 当前绝对值A > B   推的百分比为0.25   如果上一次百分比为1 ，推的百分比为0.5  ，如果上一次百分比为0.5 推的百分比为0.25

                            //-- >= 大于或等于第三次
                            //-- 推的百分比为都为0.25


                            if (lastMany.Count == 1)
                            {
                                if (ratioList.Count > 0)
                                {

                                    ration = basiRation * float.Parse(ratioList[2 - 1]);
                                }
                                if (Math.Abs((decimal)last.AY) > Math.Abs((decimal)last.BY)
                                    && Math.Abs((decimal)eQU_COM_DEFINITION_TASK_RECORD.AY) > Math.Abs((decimal)eQU_COM_DEFINITION_TASK_RECORD.BY)
                                    )
                                {
                                    pushPercentage = (float)1 * ration;
                                }
                                if (Math.Abs((decimal)last.AY) > Math.Abs((decimal)last.BY)
                                     && Math.Abs((decimal)eQU_COM_DEFINITION_TASK_RECORD.AY) < Math.Abs((decimal)eQU_COM_DEFINITION_TASK_RECORD.BY)
                                     )
                                {
                                    pushPercentage = (float)0.5 * ration;
                                }

                                if (Math.Abs((decimal)last.AY) < Math.Abs((decimal)last.BY)
                                    && Math.Abs((decimal)eQU_COM_DEFINITION_TASK_RECORD.AY) < Math.Abs((decimal)eQU_COM_DEFINITION_TASK_RECORD.BY)
                                    )
                                {
                                    pushPercentage = (float)1 * ration;
                                }
                                if (Math.Abs((decimal)last.AY) < Math.Abs((decimal)last.BY)
                                     && Math.Abs((decimal)eQU_COM_DEFINITION_TASK_RECORD.AY) > Math.Abs((decimal)eQU_COM_DEFINITION_TASK_RECORD.BY)
                                     )
                                {
                                    pushPercentage = (float)0.5 * ration;
                                }

                            }
                            if (lastMany.Count == 2)
                            {
                                if (ratioList.Count > 1)
                                {

                                    ration = basiRation * float.Parse(ratioList[3 - 1]);
                                }

                                if (Math.Abs((decimal)last.AY) > Math.Abs((decimal)last.BY)
                                    && Math.Abs((decimal)eQU_COM_DEFINITION_TASK_RECORD.AY) > Math.Abs((decimal)eQU_COM_DEFINITION_TASK_RECORD.BY)
                                    )
                                {
                                    if (last.ABInstance == 1)
                                    {
                                        pushPercentage = (float)1 * ration;
                                    }
                                    if (last.ABInstance == 0.5)
                                    {
                                        pushPercentage = (float)0.5 * ration;
                                    }
                                }
                                if (Math.Abs((decimal)last.AY) > Math.Abs((decimal)last.BY)
                                     && Math.Abs((decimal)eQU_COM_DEFINITION_TASK_RECORD.AY) < Math.Abs((decimal)eQU_COM_DEFINITION_TASK_RECORD.BY)
                                     )
                                {
                                    if (last.ABInstance == 1)
                                    {
                                        pushPercentage = (float)0.5 * ration;
                                    }
                                    if (last.ABInstance == 0.5)
                                    {
                                        pushPercentage = (float)0.25 * ration;
                                    }
                                }

                                if (Math.Abs((decimal)last.AY) < Math.Abs((decimal)last.BY)
                                    && Math.Abs((decimal)eQU_COM_DEFINITION_TASK_RECORD.AY) < Math.Abs((decimal)eQU_COM_DEFINITION_TASK_RECORD.BY)
                                    )
                                {
                                    if (last.ABInstance == 1)
                                    {
                                        pushPercentage = (float)1 * ration;
                                    }
                                    if (last.ABInstance == 0.5)
                                    {
                                        pushPercentage = (float)0.5 * ration;
                                    }
                                }
                                if (Math.Abs((decimal)last.AY) < Math.Abs((decimal)last.BY)
                                     && Math.Abs((decimal)eQU_COM_DEFINITION_TASK_RECORD.AY) > Math.Abs((decimal)eQU_COM_DEFINITION_TASK_RECORD.BY)
                                     )
                                {
                                    if (last.ABInstance == 1)
                                    {
                                        pushPercentage = (float)0.5 * ration;
                                    }
                                    if (last.ABInstance == 0.5)
                                    {
                                        pushPercentage = (float)0.25 * ration;
                                    }
                                }
                                pushPercentage = (float)float.Parse("0.5") * ration;
                            }
                            if (lastMany.Count > 2)
                            {
                                if (ratioList.Count > 2)
                                {
                                    ration = basiRation * float.Parse(ratioList[3 - 1]);
                                }
                                ration = 1 * float.Parse(ratioList[3 - 1]);
                                pushPercentage = (float)float.Parse("0.5") * ration;
                            }
                        }
                        //2.计算完发送数据给PLC
                        foreach (var plcMl in li)
                        {
                            if (plcMl.DbBlockType == "Send")
                            {
                                if (plcMl.DataType == "Real")
                                {
                                    if (plcMl.PlcNameZH == "推棒百分比")
                                    {
                                        plcHelper3.WriteReal((int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(pushPercentage.ToString()));
                                    }
                                }
                                if (plcMl.DataType == "Bit")
                                {
                                    if (plcMl.PlcNameZH == "Mes推棒百分比已发送")
                                    {
                                        var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                        plcHelper3.WriteBool((int)plcMl.DbBlock, (int)plcMl.Offset, true, DataType.DataBlock, byte.Parse(biAdr.ToString()));
                                    }
                                }
                                if (plcMl.DataType == "Real")
                                {
                                    if (plcMl.PlcNameZH == "推棒第一次Send")
                                    {
                                        var num = float.Parse((fristPush + 1).ToString());
                                        plcHelper3.WriteReal((int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse((fristPush + 1).ToString()));
                                    }
                                }
                            }
                        }
                        WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
                        {
                            if (eQU_COM_DEFINITION_TASK_RECORD != null)
                            {
                                //await repository.DbContext.AddAsync<EQU_TOOL>(mladd); 
                                eQU_COM_DEFINITION_TASK_RECORD.ABInstance = pushPercentage;
                                eQU_COM_DEFINITION_TASK_RECORD.CreateOn = DateTime.Now;
                                eQU_COM_DEFINITION_TASK_RECORD.CreateBy = "PushCart";
                                eQU_COM_DEFINITION_TASK_RECORD.OrderCode = fristPush.ToString();
                                if (fristPush == 1)
                                {
                                    eQU_COM_DEFINITION_TASK_RECORD.Description = fristPush + "PushCart" + DateTime.Now.ToString("yyyy-MM-dddd-ss-ffff");
                                }
                                else
                                {
                                    eQU_COM_DEFINITION_TASK_RECORD.Description = last.Description;
                                }
                                webResponse.Data = eQU_COM_DEFINITION_TASK_RECORD.Serialize();
                                repository.DbContext.Set<EQU_COM_DEFINITION_TASK_RECORD>().Add(eQU_COM_DEFINITION_TASK_RECORD);
                                repository.DbContext.SaveChanges();
                                //   repository.AddRange<EQU_FAULT_PHENOMENON>(eQU_FAULT_PHENOMENON, true);
                            }
                            return webResponse.OK(ResponseType.Success);
                        });
                    }

                }
                // Logger.Info(LoggerType.Success, eQU_EQUIPMENT.Serialize(), webResponse.Message, msg);
                return webResponse.OK(ResponseType.Success);

            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;

                //    Logger.Info(LoggerType.Exception, eQU_EQUIPMENT.Serialize(), webResponse.Message, msg);
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {
                plcHelper3.ClosePlc(PlcHelper.Instance.Plc);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<WebResponseContent> LoadToolSate()
        {
            var inteconfig = QueryInteConfigure("EquMeasureAuto");
            if (inteconfig == null)
            {
                webResponse.Data = $"测量仪配置没有开启！";
                return webResponse.Error($"测量仪配置没有开启！");
            }

            string msg = string.Empty;
            var li = await repository.FindAsync<EQU_PLCConfig>(t => t.PlcIP == "192.168.1.3" &&
            t.PlcNameZH.Contains("传感器信号组") || t.PlcNameZH == "上料车回原点到位" || t.PlcNameZH == "找正车回原点到位" || t.PlcNameZH == "机器人回原点到位"
            || t.PlcNameZH.Contains("大车当前位置") || t.PlcNameZH.Contains("找正车当前位置") || t.PlcNameZH.Contains("机械手当前位置"));
            EQU_TOOL eQU_EQUIPMENT = null;
            EQU_Holder eQU_Holder = null;///
            EQU_ACCESSORY eQU_ACCESSORY1 = null;
            EQU_ACCESSORY eQU_ACCESSORY2 = null;
            EQU_ACCESSORY eQU_ACCESSORY3 = null;

            try
            {
                var plcMStart = li.Where(t => t.PlcNameZH == "传感器信号组1(30)").FirstOrDefault();// section["Ip"];

                var shelvelist = await repository.FindAsync<INTE_SHELVES>(t => t.ShelfNameZH.Contains("中央刀库货架A"));
                List<string> equs = new List<string>();
                equs.Add("机器人");
                equs.Add("校正车");
                equs.Add("上下料口");
                var eQU_EQUIPMENTs = await repository.FindAsync<EQU_EQUIPMENT>(t => equs.Contains(t.EquipmentNameZH));
                if (plcMStart != null)
                {
                    var ip = string.Empty;

                    if (plcMStart != null)
                    {
                        ip = plcMStart.PlcIP;
                        var isConnect = IsIpConnect(ip);
                        if (!isConnect)
                        {
                            webResponse.Data = $"{ip}连接不上！";
                            return webResponse.Error($"{ip}连接不上！");

                        }
                    }
                    S7.Net.Plc plc = PlcHelper.Instance.Plc;
                    if (plc == null)
                    {
                        var isOpen = PlcHelper.Instance.OpenPlc(CpuType.S71500, 0, 1, ip);
                        plc = PlcHelper.Instance.Plc;
                    }
                    if (plc.IsConnected)
                    { }
                    else
                    {
                        plc.Open();

                    }
                    var rfidplc = string.Empty;
                    foreach (var plcMl in li)
                    {
                        if (plcMl.DbBlockType == "Receive")
                        {
                            if (plcMl.DataType == "Bit")
                            {
                                if (plcMl.PlcNameZH.Contains("传感器信号组1"))
                                {
                                    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                    var fristshelve = shelvelist.Where(t => t.DBCode == plcMl.DBCode).FirstOrDefault();
                                    if (fristshelve != null)
                                    {
                                        fristshelve.Status = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                                        if(fristshelve.Status == "True")
                                        {
                                            fristshelve.OrderCode = "";
                                            fristshelve.RfidCode = "";
                                        }
                                    
                                    }

                                }
                                if (plcMl.PlcNameZH.Contains("上料车回原点到位") || plcMl.PlcNameZH.Contains("找正车回原点到位") || plcMl.PlcNameZH.Contains("机器人回原点到位"))
                                {
                                    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                    var eQU = eQU_EQUIPMENTs.Where(t => t.Id == Guid.Parse(plcMl.EquipmentId)).FirstOrDefault();
                                    if (eQU != null)
                                    {
                                        eQU.IsBaseLocation = bool.Parse(PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString());
                                    }

                                }
                                //A63
                                //if (plcMl.PlcNameZH == "传感器信号组1(28)")
                                //{
                                //    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                //    var fristshelve = shelvelist.Where(t => t.DBCode == 28).FirstOrDefault();
                                //    fristshelve.Status = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();

                                //}
                                //if (plcMl.PlcNameZH == "传感器信号组1(29)")
                                //{
                                //    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                                //    var fristshelve = shelvelist.Where(t => t.DBCode == 29).FirstOrDefault();
                                //    fristshelve.Status = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();

                                //}
                                //if (plcMl.PlcNameZH == "传感器信号组1(30)")
                                //{
                                //    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                                //    var fristshelve = shelvelist.Where(t => t.DBCode == 30).FirstOrDefault();
                                //    fristshelve.Status = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();

                                //}
                                //if (plcMl.PlcNameZH == "传感器信号组1(37)")
                                //{
                                //    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                                //    var fristshelve = shelvelist.Where(t => t.DBCode == 37).FirstOrDefault();
                                //    fristshelve.Status = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();

                                //}
                                //if (plcMl.PlcNameZH == "传感器信号组1(38)")
                                //{
                                //    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                                //    var fristshelve = shelvelist.Where(t => t.DBCode == 38).FirstOrDefault();
                                //    fristshelve.Status = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();

                                //}
                                //if (plcMl.PlcNameZH == "传感器信号组1(39)")
                                //{
                                //    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                                //    var fristshelve = shelvelist.Where(t => t.DBCode == 39).FirstOrDefault();
                                //    fristshelve.Status = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();

                                //}
                                //if (plcMl.PlcNameZH == "传感器信号组1(46)")
                                //{
                                //    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                                //    var fristshelve = shelvelist.Where(t => t.DBCode == 46).FirstOrDefault();
                                //    fristshelve.Status = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();

                                //}
                                //if (plcMl.PlcNameZH == "传感器信号组1(47)")
                                //{
                                //    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                                //    var fristshelve = shelvelist.Where(t => t.DBCode == 47).FirstOrDefault();
                                //    fristshelve.Status = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();

                                //}
                                //if (plcMl.PlcNameZH == "传感器信号组1(48)")
                                //{
                                //    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                                //    var fristshelve = shelvelist.Where(t => t.DBCode == 48).FirstOrDefault();
                                //    fristshelve.Status = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();

                                //}

                                ////BT40 
                                //if (plcMl.PlcNameZH == "传感器信号组1(34)")
                                //{
                                //    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                                //    var fristshelve = shelvelist.Where(t => t.DBCode == 34).FirstOrDefault();
                                //    fristshelve.Status = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();

                                //}
                                //if (plcMl.PlcNameZH == "传感器信号组1(35)")
                                //{
                                //    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                                //    var fristshelve = shelvelist.Where(t => t.DBCode == 35).FirstOrDefault();
                                //    fristshelve.Status = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();

                                //}
                                //if (plcMl.PlcNameZH == "传感器信号组1(36)")
                                //{
                                //    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                                //    var fristshelve = shelvelist.Where(t => t.DBCode == 36).FirstOrDefault();
                                //    fristshelve.Status = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();

                                //}
                                //if (plcMl.PlcNameZH == "传感器信号组1(43)")
                                //{
                                //    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                                //    var fristshelve = shelvelist.Where(t => t.DBCode == 43).FirstOrDefault();
                                //    fristshelve.Status = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();

                                //}
                                //if (plcMl.PlcNameZH == "传感器信号组1(44)")
                                //{
                                //    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                                //    var fristshelve = shelvelist.Where(t => t.DBCode == 44).FirstOrDefault();
                                //    fristshelve.Status = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();

                                //}
                                //if (plcMl.PlcNameZH == "传感器信号组1(45)")
                                //{
                                //    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                                //    var fristshelve = shelvelist.Where(t => t.DBCode == 45).FirstOrDefault();
                                //    fristshelve.Status = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();

                                //}
                                //if (plcMl.PlcNameZH == "传感器信号组1(52)")
                                //{
                                //    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                                //    var fristshelve = shelvelist.Where(t => t.DBCode == 52).FirstOrDefault();
                                //    fristshelve.Status = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();

                                //}
                                //if (plcMl.PlcNameZH == "传感器信号组1(53)")
                                //{
                                //    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                                //    var fristshelve = shelvelist.Where(t => t.DBCode == 53).FirstOrDefault();
                                //    fristshelve.Status = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();

                                //}
                                //if (plcMl.PlcNameZH == "传感器信号组1(54)")
                                //{
                                //    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);

                                //    var fristshelve = shelvelist.Where(t => t.DBCode == 54).FirstOrDefault();
                                //    fristshelve.Status = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();

                                //}

                            }

                            if (plcMl.DataType == "Real")
                            {
                                //  var v1 = (double)PlcHelper.Instance.ReadReal(6, 0);//R角度
                                var eQU = eQU_EQUIPMENTs.Where(t => t.Id == Guid.Parse(plcMl.EquipmentId)).FirstOrDefault();
                                if (eQU != null)
                                {
                                    eQU.XLocation = decimal.Parse(PlcHelper.Instance.ReadReal((int)plcMl.DbBlock, (int)plcMl.Offset).ToString());
                                }

                            }
                        }

                    }

                }
                WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
                {

                    if (shelvelist != null)
                    {
                        repository.DbContext.Set<INTE_SHELVES>().UpdateRange(shelvelist);
                        repository.DbContext.SaveChanges();

                    }
                    if (eQU_EQUIPMENTs != null)
                    {

                        repository.DbContext.Set<EQU_EQUIPMENT>().UpdateRange(eQU_EQUIPMENTs);
                        repository.DbContext.SaveChanges();
                    }
                    return webResponse.OK(ResponseType.Success);
                });

                Logger.Info(LoggerType.Success, eQU_EQUIPMENT.Serialize(), webResponse.Message, msg);
                return webResponse.OK(ResponseType.Success);

            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                {
                    throw new Exception(ex.Message + ex.StackTrace);
                }
                Logger.Info(LoggerType.Exception, eQU_EQUIPMENT.Serialize(), webResponse.Message, msg);
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {
                PlcHelper.Instance.ClosePlc(PlcHelper.Instance.Plc);
            }
        }
        /// <summary>
        /// 退库（退出整刀）
        /// </summary>
        /// <param name="eQU_TOOL"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<WebResponseContent> ConsumeMessage(EQU_EQUIPMENT eQU_TOOL, EQU_PLCConfig eQU_PLCConfig)
        {


            var isConnectUpdate1 = IsIpConnect("192.168.1.1");
            if (isConnectUpdate1 == false)
            {
                webResponse.Data = $"192.168.1.1 ping不通！";
                return webResponse.Error($"192.168.1.1 ping不通！");
            }
            string msg = string.Empty;
            List<string> strings = new List<string>();
            strings.Add("上料车回原点");
            strings.Add("找正车回原点");
            strings.Add("机器人回原点");

            try
            {
                //   var lieq = await repository.FindAsync<EQU_EQUIPMENT>(t => t.EquipmentCode == "JCR_001");
                //  var li = eQU_PLCConfig;// await repository.FindAsync<EQU_PLCConfig>(t => strings.Contains(t.PlcNameZH));
                //   EQU_EQUIPMENT eQU_EQUIPMENT = eQU_TOOL;

                //    eQU_EQUIPMENT = lieq.FirstOrDefault();
                var plcMl = eQU_PLCConfig;// li.Where(t => t.PlcNameZH == "机器人回原点").FirstOrDefault();// section["Ip"];


                if (eQU_TOOL != null && plcMl != null)
                {
                    var ip = string.Empty;

                    if (plcMl != null)
                    {
                        ip = plcMl.PlcIP;
                        var isConnect = IsIpConnect(ip);
                        if (!isConnect)
                        {
                            webResponse.Data = $"{ip}连接不上！";
                            return webResponse.Error($"{ip}连接不上！");

                        }
                    }
                    var isOpen = PlcHelper.Instance.OpenPlc(CpuType.S71500, 0, 1, ip);
                    if (plcMl.DbBlockType == "Send")
                    {
                        if (plcMl.DataType == "Bit")
                        {
                            var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                            if (plcMl.EquipmentId == eQU_TOOL.Id.ToString().ToUpper())
                            {
                                var k = eQU_TOOL.Id.ToString().ToUpper();
                                PlcHelper.Instance.WriteBool((int)plcMl.DbBlock, (int)plcMl.Offset, true, DataType.DataBlock, biAdr);
                            }
                            // plcMl.CurrentValue = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                        }

                    }

                }
                else
                {
                    Logger.Info(LoggerType.Login, "没有设备", webResponse.Message, msg);
                    return webResponse.Error("没有设备");
                }

                //WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
                //{


                //    return webResponse.OK(ResponseType.Success);
                //});


                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                {
                    throw new Exception(ex.Message + ex.StackTrace);
                }

                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {
                PlcHelper.Instance.ClosePlc(PlcHelper.Instance.Plc);
            }
        }
        /// <summary>
        /// 退库（退出整刀）
        /// </summary>
        /// <param name="eQU_TOOL"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<WebResponseContent> PlcOutStock(EQU_TOOL eQU_TOOL)
        {
            var inteconfig = QueryInteConfigure("EquMeasureAuto");
            if (inteconfig == null)
            {
                webResponse.Data = $"测量仪配置没有开启！";
                return webResponse.Error($"测量仪配置没有开启！");
            }
            var isConnectUpdate1 = IsIpConnect("192.168.1.1");
            if (isConnectUpdate1 == false)
            {
                webResponse.Data = $"192.168.1.1 ping不通！";
                return webResponse.Error($"192.168.1.1 ping不通！");
            }
            string msg = string.Empty;
            var li = await repository.FindAsync<EQU_PLCConfig>(t => t.PlcIP == "192.168.1.190");
            EQU_TOOL eQU_EQUIPMENT = null;

            try
            {
                var plcMl = li.Where(t => t.PlcNameZH == "请求退库").FirstOrDefault();// section["Ip"];
                eQU_EQUIPMENT = await repository.FindAsyncFirst<EQU_TOOL>(t => t.Id == eQU_TOOL.Id);

                if (eQU_EQUIPMENT != null && plcMl != null)
                {
                    var ip = string.Empty;

                    if (plcMl != null)
                    {
                        ip = plcMl.PlcIP;
                        var isConnect = IsIpConnect(ip);
                        if (!isConnect)
                        {
                            webResponse.Data = $"{ip}连接不上！";
                            return webResponse.Error($"{ip}连接不上！");

                        }
                    }
                    var isOpen = PlcHelper.Instance.OpenPlc(CpuType.S71500, 0, 1, ip);
                    if (plcMl.DbBlockType == "Send" && !string.IsNullOrEmpty(plcMl.CurrentWriteValue))
                    {
                        if (plcMl.DataType == "Real")
                        {
                            PlcHelper.Instance.WriteReal((int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(plcMl.CurrentWriteValue));
                        }
                        if (plcMl.DataType == "DWord")
                        {
                            PlcHelper.Instance.WriteDWord((int)plcMl.DbBlock, (int)plcMl.Offset, uint.Parse(plcMl.CurrentWriteValue));
                        }
                        if (plcMl.DataType == "Byte")
                        {
                            var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                            PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(plcMl.CurrentWriteValue));
                            plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                        }
                        if (plcMl.DataType == "Bit")
                        {
                            var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                            if (plcMl.PlcNameZH == "请求退库")
                            {
                                PlcHelper.Instance.WriteBool((int)plcMl.DbBlock, (int)plcMl.Offset, true, DataType.DataBlock, biAdr);
                            }
                            else
                            {
                                PlcHelper.Instance.WriteBool((int)plcMl.DbBlock, (int)plcMl.Offset, bool.Parse(plcMl.CurrentWriteValue), DataType.DataBlock, biAdr);
                            }
                            plcMl.CurrentValue = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                        }
                        repository.DbContext.Set<EQU_PLCConfig>().Update(plcMl);
                        repository.SaveChanges();
                    }

                }
                else
                {
                    Logger.Info(LoggerType.Login, "没有设备", webResponse.Message, msg);
                    return webResponse.Error("没有设备");
                }

                WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
                {

                    if (eQU_EQUIPMENT != null)
                    {
                        repository.DbContext.Set<EQU_TOOL>().Update(eQU_EQUIPMENT);
                        repository.DbContext.SaveChanges();

                    }
                    return webResponse.OK(ResponseType.Success);
                });

                Logger.Info(LoggerType.Success, eQU_EQUIPMENT.Serialize(), webResponse.Message, msg);
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                {
                    throw new Exception(ex.Message + ex.StackTrace);
                }
                Logger.Info(LoggerType.Exception, eQU_EQUIPMENT.Serialize(), webResponse.Message, msg);
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {
                PlcHelper.Instance.ClosePlc(PlcHelper.Instance.Plc);
            }
        }
        /// <summary>
        /// 入库（整刀）
        /// </summary>
        /// <param name="eQU_TOOL"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<WebResponseContent> PlcInStock(EQU_TOOL eQU_TOOL)
        {
            string msg = string.Empty;
            EQU_TOOL qU_TOOL  = null;
            List<INTE_SHELVES> shelvelist = null;
            var location = 0;
            var inteconfig = QueryInteConfigure("EquMeasureAuto");
            if (inteconfig == null)
            {
                webResponse.Data = $"测量仪配置没有开启！";
                return webResponse.Error($"测量仪配置没有开启！");
            }
            var isConnectUpdate1 = IsIpConnect("192.168.1.1");
            if (isConnectUpdate1 == false)
            {
                webResponse.Data = $"192.168.1.1 ping不通！";
                return webResponse.Error($"192.168.1.1 ping不通！");
            }
            //分配放刀位置
            var li3 = await repository.FindAsync<EQU_PLCConfig>(t => t.PlcIP == "192.168.1.3");
            try
            {
                var plcMl3first = li3.Where(t => t.PlcNameZH == "放刀位置编号").FirstOrDefault();// section["Ip"];
                var plcMl3lists = li3.Where(t => t.PlcNameZH == "放刀位置编号" || t.PlcNameZH == "取A63刀" || t.PlcNameZH == "取bt40刀");// section["Ip"];
                qU_TOOL = await repository.FindAsyncFirst<EQU_TOOL>(t => t.Id == eQU_TOOL.Id);
                if (qU_TOOL != null && plcMl3first != null)
                {
                    var ip = string.Empty;

                    if (plcMl3first != null)
                    {
                        ip = plcMl3first.PlcIP;
                        var isConnect = IsIpConnect(ip);
                        if (!isConnect)
                        {
                            webResponse.Data = $"{ip}连接不上！";
                            return webResponse.Error($"{ip}连接不上！");

                        }
                    }
                    var isOpen = PlcHelper.Instance.OpenPlc(CpuType.S71500, 0, 1, ip);
                    location = 0;
                    //  plcMl3.CurrentWriteValue = location.ToString(); //"30";
                    var wAREHOUSE = await repository.FindAsyncFirst<INTE_WAREHOUSE>(t => t.WarehouseNameZH.Contains("中央刀库"));
                     shelvelist = await repository.FindAsync<INTE_SHELVES>(t => t.ShelfNameZH.Contains("中央刀库货架A") && t.WarehouseId.Equals(wAREHOUSE.Id.ToString().ToUpper()));
                    //分配库位点
                    var eq = qU_TOOL.HolderTypeId;
                   
                    var shelf = shelvelist.OrderBy(t => t.DBCode).Where(t => t.HolderTypeId == eq && t.Status == "True").FirstOrDefault();
                   
                    if (shelf != null)
                    {
                        location = shelf.DBCode.Value;
                        qU_TOOL.location = location;
                        shelf.OrderCode = qU_TOOL.Identifier;
                        shelf.RfidCode = qU_TOOL.RfidCode;
                    }
                   
                    foreach (var plcMl3 in plcMl3lists)
                    {
                        if (plcMl3.DbBlockType == "Send")
                        {

                            if (plcMl3.DataType == "Word")
                            {

                                if (plcMl3.PlcNameZH == "放刀位置编号")
                                {
                                    plcMl3.CurrentWriteValue = location.ToString(); //"30";
                                    PlcHelper.Instance.WriteWord((int)plcMl3.DbBlock, (int)plcMl3.Offset, ushort.Parse(plcMl3.CurrentWriteValue));
                                     // plcMl3.CurrentValue = PlcHelper.Instance.ReadWord((int)plcMl3.DbBlock, (int)plcMl3.Offset, DataType.DataBlock).ToString();
                                }

                            }
                         

                        }
                        repository.DbContext.Set<EQU_PLCConfig>().Update(plcMl3);
                        repository.SaveChanges();
                    }
                    foreach (var plcMl3 in plcMl3lists)
                    {
                        if (plcMl3.DbBlockType == "Send")
                        {

                           
                            if (plcMl3.DataType == "Bit")
                            {//HolderTypeId
                                var biAdr = GetDecimalPlacesAsInteger((double)plcMl3.Offset.Value, 1);
                                if (plcMl3.PlcNameZH == "取bt40刀" && qU_TOOL.HolderTypeId == "BT40")
                                {
                                    PlcHelper.Instance.WriteBool((int)plcMl3.DbBlock, (int)plcMl3.Offset, true, DataType.DataBlock, biAdr);
                                }
                                else if (plcMl3.PlcNameZH == "取A63刀" && qU_TOOL.HolderTypeId == "A63")
                                {
                                    PlcHelper.Instance.WriteBool((int)plcMl3.DbBlock, (int)plcMl3.Offset, true, DataType.DataBlock, biAdr);
                                }
                                {
                                    //PlcHelper.Instance.WriteBool((int)plcMl3.DbBlock, (int)plcMl3.Offset, bool.Parse(plcMl3.CurrentWriteValue), DataType.DataBlock, biAdr);
                                }

                                //plcMl3.CurrentValue = PlcHelper.Instance.ReadBool((int)plcMl3.DbBlock, (int)plcMl3.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                            }

                        }
                        repository.DbContext.Set<EQU_PLCConfig>().Update(plcMl3);
                        repository.SaveChanges();
                    }



                }
                else
                {
                    Logger.Info(LoggerType.Login, "没有设备", webResponse.Message, msg);
                    return webResponse.Error("没有设备");
                }
                //2入库
                var li = await repository.FindAsync<EQU_PLCConfig>(t => t.PlcIP == "192.168.1.190");
                var plcMl = li.Where(t => t.PlcNameZH == "允许入库").FirstOrDefault();// section["Ip"];
             //   eQU_EQUIPMENT = await repository.FindAsyncFirst<EQU_TOOL>(t => t.Id == eQU_TOOL.Id);

                if (qU_TOOL != null && plcMl != null)
                {
                    var ip = string.Empty;

                    if (plcMl != null)
                    {
                        ip = plcMl.PlcIP;
                        var isConnect = IsIpConnect(ip);
                        if (!isConnect)
                        {
                            webResponse.Data = $"{ip}连接不上！";
                            return webResponse.Error($"{ip}连接不上！");

                        }
                    }
                    var isOpen = PlcHelper.Instance.OpenPlc(CpuType.S71500, 0, 1, ip);
                    if (plcMl.DbBlockType == "Send" && !string.IsNullOrEmpty(plcMl.CurrentWriteValue))
                    {
                        if (plcMl.DataType == "Real")
                        {
                            PlcHelper.Instance.WriteReal((int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(plcMl.CurrentWriteValue));
                        }
                        if (plcMl.DataType == "DWord")
                        {
                            PlcHelper.Instance.WriteDWord((int)plcMl.DbBlock, (int)plcMl.Offset, uint.Parse(plcMl.CurrentWriteValue));
                        }
                        if (plcMl.DataType == "Word")
                        {
                            //    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                            PlcHelper.Instance.WriteWord((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(plcMl.CurrentWriteValue));
                            plcMl.CurrentValue = PlcHelper.Instance.ReadWord((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock).ToString();
                        }
                        if (plcMl.DataType == "Byte")
                        {
                            var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                            PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(plcMl.CurrentWriteValue));
                            plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                        }
                        if (plcMl.DataType == "Bit")
                        {
                            var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                            if (plcMl.PlcNameZH == "允许入库")
                            {
                                PlcHelper.Instance.WriteBool((int)plcMl.DbBlock, (int)plcMl.Offset, true, DataType.DataBlock, biAdr);
                            }
                            else
                            {
                                PlcHelper.Instance.WriteBool((int)plcMl.DbBlock, (int)plcMl.Offset, bool.Parse(plcMl.CurrentWriteValue), DataType.DataBlock, biAdr);
                            }

                            plcMl.CurrentValue = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                        }
                        repository.DbContext.Set<EQU_PLCConfig>().Update(plcMl);
                        repository.SaveChanges();
                    }

                }


                WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
                {
                    if(shelvelist != null)
                    {
                        repository.DbContext.Set<INTE_SHELVES>().UpdateRange(shelvelist);
                        repository.DbContext.SaveChanges();
                    }
                    if (qU_TOOL != null)
                    {
                        repository.DbContext.Set<EQU_TOOL>().Update(qU_TOOL);
                        repository.DbContext.SaveChanges();

                    }
                    return webResponse.OK(ResponseType.Success);
                });

                Logger.Info(LoggerType.Success, qU_TOOL.Serialize(), webResponse.Message, msg);
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                {
                    throw new Exception(ex.Message + ex.StackTrace);
                }
                Logger.Info(LoggerType.Exception, qU_TOOL.Serialize(), webResponse.Message, msg);
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {
                PlcHelper.Instance.ClosePlc(PlcHelper.Instance.Plc);
            }
            /*

            try
            {
                var li = await repository.FindAsync<EQU_PLCConfig>(t => t.PlcIP == "192.168.1.190");
                var plcMl = li.Where(t => t.PlcNameZH == "允许入库").FirstOrDefault();// section["Ip"];
                qU_TOOL = await repository.FindAsyncFirst<EQU_TOOL>(t => t.Id == eQU_TOOL.Id);

                if (qU_TOOL != null && plcMl != null)
                {
                    var ip = string.Empty;

                    if (plcMl != null)
                    {
                        ip = plcMl.PlcIP;
                        var isConnect = IsIpConnect(ip);
                        if (!isConnect)
                        {
                            webResponse.Data = $"{ip}连接不上！";
                            return webResponse.Error($"{ip}连接不上！");

                        }
                    }
                    var isOpen = PlcHelper.Instance.OpenPlc(CpuType.S71500, 0, 1, ip);
                    if (plcMl.DbBlockType == "Send" && !string.IsNullOrEmpty(plcMl.CurrentWriteValue))
                    {
                        if (plcMl.DataType == "Real")
                        {
                            PlcHelper.Instance.WriteReal((int)plcMl.DbBlock, (int)plcMl.Offset, float.Parse(plcMl.CurrentWriteValue));
                        }
                        if (plcMl.DataType == "DWord")
                        {
                            PlcHelper.Instance.WriteDWord((int)plcMl.DbBlock, (int)plcMl.Offset, uint.Parse(plcMl.CurrentWriteValue));
                        }
                        if (plcMl.DataType == "Word")
                        {
                            //    var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                            PlcHelper.Instance.WriteWord((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(plcMl.CurrentWriteValue));
                            plcMl.CurrentValue = PlcHelper.Instance.ReadWord((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock).ToString();
                        }
                        if (plcMl.DataType == "Byte")
                        {
                            var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                            PlcHelper.Instance.WriteByte((int)plcMl.DbBlock, (int)plcMl.Offset, byte.Parse(plcMl.CurrentWriteValue));
                            plcMl.CurrentValue = PlcHelper.Instance.ReadByte((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                        }
                        if (plcMl.DataType == "Bit")
                        {
                            var biAdr = GetDecimalPlacesAsInteger((double)plcMl.Offset.Value, 1);
                            if (plcMl.PlcNameZH == "允许入库")
                            {
                                PlcHelper.Instance.WriteBool((int)plcMl.DbBlock, (int)plcMl.Offset, true, DataType.DataBlock, biAdr);
                            }
                            else
                            {
                                PlcHelper.Instance.WriteBool((int)plcMl.DbBlock, (int)plcMl.Offset, bool.Parse(plcMl.CurrentWriteValue), DataType.DataBlock, biAdr);
                            }

                            plcMl.CurrentValue = PlcHelper.Instance.ReadBool((int)plcMl.DbBlock, (int)plcMl.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                        }
                        repository.DbContext.Set<EQU_PLCConfig>().Update(plcMl);
                        repository.SaveChanges();
                    }

                }
                else
                {
                    Logger.Info(LoggerType.Login, "没有设备", webResponse.Message, msg);
                    return webResponse.Error("没有设备");
                }


                WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
                {

                    if (qU_TOOL != null)
                    {
                        repository.DbContext.Set<EQU_TOOL>().Update(qU_TOOL);
                        repository.DbContext.SaveChanges();

                    }
                    return webResponse.OK(ResponseType.Success);
                });

                Logger.Info(LoggerType.Success, qU_TOOL.Serialize(), webResponse.Message, msg);
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                {
                    throw new Exception(ex.Message + ex.StackTrace);
                }
                Logger.Info(LoggerType.Exception, qU_TOOL.Serialize(), webResponse.Message, msg);
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {
                PlcHelper.Instance.ClosePlc(PlcHelper.Instance.Plc);
            }
            */
        }
        /// <summary>
        /// 设备是否在线
        /// </summary>
        /// <returns></returns>
        public async Task<WebResponseContent> EquIsPing()
        {
            var res = new PlcPlan();
            var isEable1 = false;
            var isEable2 = false;
            var isEable3 = false;
            var isException1 = false;
            var isException2 = false;
            var isException3 = false;
            string msg = string.Empty;
            List<EQU_FAULT_PHENOMENON> eQU_FAULT_PHENOMENONs = new List<EQU_FAULT_PHENOMENON>();
            var isConnectUpdate = IsIpConnect("192.168.110.183");
            var isConnectUpdate1 = IsIpConnect("192.168.1.3");
            if (isConnectUpdate1 == false)
            {
                webResponse.Data = $"192.168.1.1 ping不通！";
                return webResponse.Error($"192.168.1.1 ping不通！");
            }
            var li3config = await repository.FindAsync<EQU_PLCConfig>(t => t.PlcIP == "192.168.1.3");
            List<string> arryEnables = new List<string>();
            arryEnables.Add("总线使能就绪");
            arryEnables.Add("推棒使能就绪");
            arryEnables.Add("上料车使能就绪");
            arryEnables.Add("机器人就绪使能");
            arryEnables.Add("机器人异常");
            arryEnables.Add("校正车异常");
            arryEnables.Add("上料车异常");
            //分配放刀位置
            var li3 = await repository.FindAsync<EQU_EQUIPMENT>(t => string.IsNullOrEmpty(t.host) != true);

            try
            {
                if (li3.Count == 0)
                {
                    return webResponse.Error(ResponseType.ServerError);
                }
                var ip = string.Empty;

                var plcMl3first = li3config.Where(t => arryEnables.Contains(t.PlcNameZH)).FirstOrDefault();
                var plcMl3lists = li3config.Where(t => arryEnables.Contains(t.PlcNameZH));
                if (plcMl3first != null)
                {
                    //var ip = string.Empty;

                    if (plcMl3first != null)
                    {
                        ip = plcMl3first.PlcIP;
                        var isConnect = IsIpConnect(ip);
                        if (!isConnect)
                        {
                            webResponse.Data = $"{ip}连接不上！";
                            return webResponse.Error($"{ip}连接不上！");

                        }
                    }
                    var isOpen = PlcHelper.Instance.OpenPlc(CpuType.S71500, 0, 1, ip);
                    foreach (var plcMl3 in plcMl3lists)
                    {
                        if (plcMl3.DbBlockType == "Receive")
                        {
                            if (plcMl3.DataType == "Bit")
                            {
                                var biAdr = GetDecimalPlacesAsInteger((double)plcMl3.Offset.Value, 1);
                                if (plcMl3.PlcNameZH == "推棒使能就绪")
                                {
                                    isEable1 = PlcHelper.Instance.ReadBool((int)plcMl3.DbBlock, (int)plcMl3.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString()));
                                }
                                if (plcMl3.PlcNameZH == "上料车使能就绪")
                                {
                                    isEable2 = PlcHelper.Instance.ReadBool((int)plcMl3.DbBlock, (int)plcMl3.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString()));
                                }
                                if (plcMl3.PlcNameZH == "机器人就绪使能")
                                {
                                    isEable3 = PlcHelper.Instance.ReadBool((int)plcMl3.DbBlock, (int)plcMl3.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString()));
                                }
                                if (plcMl3.PlcNameZH == "机器人异常")
                                {
                                    isException1 = PlcHelper.Instance.ReadBool((int)plcMl3.DbBlock, (int)plcMl3.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString()));
                                }
                                if (plcMl3.PlcNameZH == "校正车异常")
                                {
                                    isException2 = PlcHelper.Instance.ReadBool((int)plcMl3.DbBlock, (int)plcMl3.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString()));
                                }
                                if (plcMl3.PlcNameZH == "上料车异常")
                                {
                                    isException3 = PlcHelper.Instance.ReadBool((int)plcMl3.DbBlock, (int)plcMl3.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString()));
                                }
                                //plcMl3.CurrentValue = PlcHelper.Instance.ReadBool((int)plcMl3.DbBlock, (int)plcMl3.Offset, DataType.DataBlock, byte.Parse(biAdr.ToString())).ToString();
                            }
                        }
                    }
                }
                foreach (var item in li3)
                {
                    ip = item.host;
                    var isConnect = IsIpConnect(ip);
                    if (!isConnect)
                    {
                        item.IsOnline = false;
                    }
                    else
                    {
                        item.IsOnline = true;

                    }
                    if (item.EquipmentCode == "SLK_001")//上下料口
                    {
                        item.IsEnable = isEable1;
                        item.IsException = isException3;
                    }
                    if (item.EquipmentCode == "JZC_001")//校正车
                    {
                        item.IsEnable = isEable2;
                        item.IsException = isException2;
                    }
                    if (item.EquipmentCode == "JCR_001")//机器人
                    {
                        item.IsEnable = isEable3;
                        item.IsException = isException1;
                    }
                }
                if (isConnectUpdate && isConnectUpdate1)
                {

                    repository.DbContext.Set<EQU_EQUIPMENT>().UpdateRange(li3);
                    var li3false = li3.Where(t => t.IsEnable == false).ToList();
                    foreach (var item in li3false)
                    {
                        if (item.EquipmentCode == "JCR_001")
                        {
                            var taskli = await repository.FindAsync<EQU_COM_DEFINITION_TASK_DETECTION>(t => t.Status == "2" && (t.Command == "TW004" || t.Command == "TW0031"));
                            foreach (var task in taskli)
                            {
                                var plan_work_order = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.OrderCode == task.OrderCode);
                                task.Status = "4";
                                task.LastUpdateOn = DateTime.Now;
                                task.UpdateBy = "system";
                                task.Description = "【" + item.EquipmentNameZH + "】设备使能未就绪";
                                repository.DbContext.Set<EQU_COM_DEFINITION_TASK_DETECTION>().Update(task);
                                //电气设备异常
                                EQU_FAULT_PHENOMENON eQU_FAULT_PHENOMENON = new EQU_FAULT_PHENOMENON();
                                eQU_FAULT_PHENOMENON.TaskNo = task.TaskNo;
                                eQU_FAULT_PHENOMENON.Content = task.Description;
                                eQU_FAULT_PHENOMENON.FunctionType = "电气设备异常";
                                eQU_FAULT_PHENOMENON.OrderId = plan_work_order != null ? plan_work_order.Order_Id.ToString().ToUpper() : null;
                                eQU_FAULT_PHENOMENON.CreateOn = DateTime.Now;
                                eQU_FAULT_PHENOMENONs.Add(eQU_FAULT_PHENOMENON);
                            }
                        }
                        if (item.EquipmentCode == "JZC_001")
                        {
                            var taskli = await repository.FindAsync<EQU_COM_DEFINITION_TASK_DETECTION>(t => t.Status == "2" && (t.Command == "TW0032"));
                            foreach (var task in taskli)
                            {
                                var plan_work_order = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.OrderCode == task.OrderCode);
                                task.Status = "4";
                                task.LastUpdateOn = DateTime.Now;
                                task.UpdateBy = "system";
                                task.Description = "【" + item.EquipmentNameZH + "】设备使能未就绪";
                                repository.DbContext.Set<EQU_COM_DEFINITION_TASK_DETECTION>().Update(task);
                                //电气设备异常
                                EQU_FAULT_PHENOMENON eQU_FAULT_PHENOMENON = new EQU_FAULT_PHENOMENON();
                                eQU_FAULT_PHENOMENON.TaskNo = task.TaskNo;
                                eQU_FAULT_PHENOMENON.Content = task.Description;
                                eQU_FAULT_PHENOMENON.FunctionType = "电气设备异常";
                                eQU_FAULT_PHENOMENON.OrderId = plan_work_order != null ? plan_work_order.Order_Id.ToString().ToUpper() : null;
                                eQU_FAULT_PHENOMENON.CreateOn = DateTime.Now;
                                eQU_FAULT_PHENOMENONs.Add(eQU_FAULT_PHENOMENON);
                            }
                        }
                        if (item.EquipmentCode == "SLK_001")
                        {
                            var taskli = await repository.FindAsync<EQU_COM_DEFINITION_TASK_DETECTION>(t => t.Status == "2" && (t.Command == "TW003"));
                            foreach (var task in taskli)
                            {
                                var plan_work_order = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.OrderCode == task.OrderCode);
                                task.Status = "4";
                                task.LastUpdateOn = DateTime.Now;
                                task.UpdateBy = "system";
                                task.Description = "【" + item.EquipmentNameZH + "】设备使能未就绪";
                                repository.DbContext.Set<EQU_COM_DEFINITION_TASK_DETECTION>().Update(task);
                                //电气设备异常
                                EQU_FAULT_PHENOMENON eQU_FAULT_PHENOMENON = new EQU_FAULT_PHENOMENON();
                                eQU_FAULT_PHENOMENON.TaskNo = task.TaskNo;
                                eQU_FAULT_PHENOMENON.Content = task.Description;
                                eQU_FAULT_PHENOMENON.FunctionType = "电气设备异常";
                                eQU_FAULT_PHENOMENON.OrderId = plan_work_order != null ? plan_work_order.Order_Id.ToString().ToUpper() : null;
                                eQU_FAULT_PHENOMENON.CreateOn = DateTime.Now;
                                eQU_FAULT_PHENOMENONs.Add(eQU_FAULT_PHENOMENON);
                            }
                        }
                    }
                    //if(eQU_FAULT_PHENOMENONs.Count>0)
                    //{
                    //    repository.DbContext.Set<EQU_FAULT_PHENOMENON>().AddRange(eQU_FAULT_PHENOMENONs);
                    //}
                    repository.SaveChanges();
                }

                Logger.Info(LoggerType.Success, res.Serialize(), webResponse.Message, msg);
                webResponse.Data = res;
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {

                Logger.Info(LoggerType.Exception, res.Serialize(), webResponse.Message, msg);
                return webResponse.Error(ResponseType.ServerError);
            }




        }
       /// <summary>
       /// 
       /// </summary>
       /// <param name="eQU_TOOL"></param>
       /// <returns></returns>
        public async Task<WebResponseContent> PlcRestart()
        {
            var res = new PlcPlan();
            PlcHelper plcHelper190 = new PlcHelper();
            string msg = string.Empty;
            Thread.Sleep(200); // 模拟工作
            var isConnectUpdate1 = IsIpConnect("192.168.1.1");
            if (isConnectUpdate1 == false)
            {
                webResponse.Data = $"192.168.1.1 ping不通！";
                return webResponse.Error($"192.168.1.1 ping不通！");
            }
            EQU_TOOL_Measure eQU_TOOL_Measure = await repository.FindAsyncFirst<EQU_TOOL_Measure>(t => t.tool_name != null);
            var li190 = await repository.FindAsync<EQU_PLCConfig>(t => t.PlcNameZH == "对刀仪准备启动BT40" || t.PlcNameZH == "对刀仪准备启动A63" );
            var li190list = li190.ToList();

           
            try
            {

                try
                {
                    var ip = string.Empty;
                    if (li190list != null && li190list.Count > 0)
                    {
                        ip = li190list.FirstOrDefault().PlcIP;



                        var isOpen = PlcHelper190.Instance.OpenPlc(CpuType.S71500, 0, 1, ip);
                        if (isOpen == true)
                        {

                            foreach (var plcMl3 in li190list)
                            {
                                
                                if (plcMl3.DbBlockType == "Send")
                                {
                                    if (plcMl3.DataType == "Bit")
                                    {
                                        var biAdr = GetDecimalPlacesAsInteger((double)plcMl3.Offset.Value, 1);
                                    
                                        if (plcMl3.PlcNameZH == "对刀仪准备启动BT40" && eQU_TOOL_Measure.HolderTypeId == "BT40")
                                        {
                                          
                                            PlcHelper190.Instance.WriteBool((int)plcMl3.DbBlock, (int)plcMl3.Offset,true, DataType.DataBlock, biAdr);
                                            Thread.Sleep(200); // 模拟工作
                                        }
                                        if (plcMl3.PlcNameZH == "对刀仪准备启动A63" && eQU_TOOL_Measure.HolderTypeId == "A63")
                                        {
                                            PlcHelper190.Instance.WriteBool((int)plcMl3.DbBlock, (int)plcMl3.Offset, true, DataType.DataBlock, biAdr);
                                            Thread.Sleep(200); // 模拟工作

                                        }


                                    }
                                }
                            }
                        }
                    }
                    // Logger.Info(LoggerType.Success, res.Serialize(), webResponse.Message, msg);
                    //  webResponse.Data = res;
                    //  return webResponse.OK(ResponseType.Success);
                }
                catch (Exception ex)
                {

                    // return webResponse.Error(ResponseType.ServerError);
                }
                finally
                {
                    PlcHelper190.Instance.ClosePlc(PlcHelper190.Instance.Plc);
                }

               
             
                webResponse.Data = res;
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {

                Logger.Info(LoggerType.Exception, eQU_TOOL_Measure.Serialize(), webResponse.Message, msg);
                return webResponse.Error(ResponseType.ServerError);
            }
            



        }
        /// <summary>
        /// 入库（整刀）Auto
        /// </summary>
        /// <param name="eQU_TOOL"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<WebResponseContent> PlcVeiwPlanAuto()
        {
            var res = new PlcPlan();
            PlcHelper plcHelper190 = new PlcHelper();
            string msg = string.Empty;
            var isConnectUpdate1 = IsIpConnect("192.168.1.1");
            if (isConnectUpdate1 == false)
            {
                webResponse.Data = $"192.168.1.1 ping不通！";
                return webResponse.Error($"192.168.1.1 ping不通！");
            }
            EQU_TOOL_Measure eQU_TOOL_Measure = await repository.FindAsyncFirst<EQU_TOOL_Measure>(t => t.tool_name != null&&t.RfidCode!="");
            if(eQU_TOOL_Measure != null)
            {
                EQU_TOOL eQU_TOOL = await repository.FindAsyncFirst<EQU_TOOL>(t =>t.RfidCode== eQU_TOOL_Measure.RfidCode&& t.tool_name == eQU_TOOL_Measure.tool_name&&t.Identifier== eQU_TOOL_Measure.Identifier);
                
                
                if (eQU_TOOL!=null)
                {
                    EQU_ACCESSORY eQU_ACCESSORY1 = await repository.FindAsyncFirst<EQU_ACCESSORY>(t => t.AccessorieCode == eQU_TOOL.Accessorie1Code);
                    EQU_Holder eQU_Holder = await repository.FindAsyncFirst<EQU_Holder>(t => t.Holder_Code == eQU_TOOL.handle_type);
                    eQU_TOOL_Measure.Accessorie1Code = eQU_TOOL.Accessorie1Code;
                    eQU_TOOL_Measure.Accessorie2Code = eQU_TOOL.Accessorie2Code;
                    eQU_TOOL_Measure.Accessorie3_Code = eQU_TOOL.Accessorie3_Code;
                    eQU_TOOL_Measure.handle_type= eQU_TOOL.handle_type;

                    eQU_TOOL_Measure.reality_knife_width = eQU_TOOL.reality_knife_width;
                    eQU_TOOL_Measure.knife_width = eQU_TOOL.knife_width;
                    eQU_TOOL_Measure.knife_length = eQU_TOOL.knife_length;
                    eQU_TOOL_Measure.reality_knife_length = eQU_TOOL.reality_knife_length;                    
                    if(eQU_Holder!=null)
                    {
                        eQU_TOOL_Measure.HolderLTheory = eQU_Holder.HolderLTheory;                       
                    }
                    eQU_TOOL_Measure.HolderBDTheory = eQU_TOOL.HolderBDTheory;
                    eQU_TOOL_Measure.HolderL = eQU_TOOL.HolderL;
                    eQU_TOOL_Measure.vendor_code = eQU_TOOL.Id.ToString();
                    eQU_TOOL_Measure.HolderBD = eQU_TOOL.HolderBD;
                    eQU_TOOL_Measure.Ace1LTheory = eQU_TOOL.Ace1LTheory;
                    eQU_TOOL_Measure.Ace1L = eQU_TOOL.Ace1L;

                    //Ace1LTheory,Ace1L,
                    //HolderBD,HolderBDTheory


                }
            }
            else
            {
                webResponse.Data = $"没有刀具信息！";
                return webResponse.Error($"没有刀具信息！");
            }



           
            //repository.DbContext.Set<EQU_TOOL_Measure>().Update(eQU_TOOL_Measure);
            //repository.SaveChanges();
            //Logger.Info(LoggerType.Success, res.Serialize(), webResponse.Message, msg);

            webResponse.Data = res;
            return webResponse.OK(ResponseType.Success);


        }
        /// <summary>
        /// 入库（整刀）
        /// </summary>
        /// <param name="eQU_TOOL"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<WebResponseContent> PlcVeiwPlan(ICacheService _cache)
        {
            var res = new PlcPlan();
            PlcHelper plcHelper190 = new PlcHelper();
            string msg = string.Empty;
            
            EQU_TOOL_Measure eQU_TOOL_Measure =await repository.FindAsyncFirst<EQU_TOOL_Measure>(t => t.tool_name != null);

            if(eQU_TOOL_Measure!=null)
            {
                var eQU_TOOL = await repository.FindAsyncFirst<EQU_TOOL>(t => t.tool_name != null&&t.RfidCode==eQU_TOOL_Measure.RfidCode);
                res.tool_name = eQU_TOOL_Measure.tool_name;
                res.HolderL = eQU_TOOL_Measure.HolderL;
                res.Holder_Code=eQU_TOOL_Measure.Holder_Code;
                res.location=eQU_TOOL_Measure.location;
                res.Identifier=eQU_TOOL_Measure.Identifier;
                res.R= eQU_TOOL_Measure.R;
                res.reality_knife_length = eQU_TOOL_Measure.reality_knife_length;
                res.reality_pairing_length= eQU_TOOL_Measure.reality_pairing_length;
                res.HolderTypeId=eQU_TOOL_Measure.HolderTypeId;
                res.RfidCode = eQU_TOOL_Measure.RfidCode;
                res.handle_type= eQU_TOOL_Measure.handle_type;
                res.IsUse = eQU_TOOL_Measure.IsUse;
                res.IsWriteRfid = eQU_TOOL_Measure.IsWriteRfid;
                res.IsFalut = eQU_TOOL_Measure.IsFalut;
                res.IsKnifeCompleted = eQU_TOOL_Measure.IsKnifeCompleted;
                res.IsKnifeOngoing = eQU_TOOL_Measure.IsKnifeOngoing;
                res.FaultNo = eQU_TOOL_Measure.FaultNo;
                res.KnifeLocationNumber = eQU_TOOL_Measure.KnifeLocationNumber;
                res.FaultNoMeasure=eQU_TOOL_Measure.FaultNoMeasure;
                res.knife_width= eQU_TOOL_Measure.knife_width;//理论刀宽
                res.reality_knife_width = eQU_TOOL_Measure.reality_knife_width;//实际刀宽
                res.knife_length = eQU_TOOL_Measure.knife_length;//理论刀长
                res.reality_knife_length= eQU_TOOL_Measure.reality_knife_length; //实际刀长

                res.HolderLTheory = eQU_TOOL_Measure.HolderLTheory;
                res.HolderL = eQU_TOOL_Measure.HolderL;
                res.Ace1LTheory = eQU_TOOL_Measure.Ace1LTheory;
                res.Ace1L = eQU_TOOL_Measure.Ace1L;
                res.Description= eQU_TOOL_Measure.Description;
                res.vendor_code = eQU_TOOL_Measure.vendor_code;//Id
                res.isInOut= eQU_TOOL_Measure.IsInOut;
                res.togetherSeq= eQU_TOOL_Measure.TogetherSeq.ToString();
                res.sys_DictionaryLists = _cache.Get<List<Sys_DictionaryList>>("对刀仪报警");
                if(eQU_TOOL!=null)
                {
                    res.measureStartTime = eQU_TOOL.MeasureStartTime==null?"-": eQU_TOOL.MeasureStartTime.ToString();
                    res.measureEndTime = eQU_TOOL.MeasureEndTime==null?"-": eQU_TOOL.MeasureStartTime.ToString();
                }
                else { 
                    res.measureStartTime = "-";
                    res.measureEndTime = "-";
                }                

            }         
                webResponse.Data = res;
                return webResponse.OK(ResponseType.Success);
 
        }
        #endregion
        /// <summary>
        /// 排产检查
        /// </summary>
        /// <param name="pLAN_WORK_ORDER"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<WebResponseContent> OrderPlanCheck(PLAN_WORK_ORDER pLAN_WORK_ORDER)
        {
            string msg = string.Empty;
            string desc = string.Empty;
            try
            {

                //
                var speedArry = new List<string>();//转速
                speedArry.Add("8000");
                speedArry.Add("12000");
                speedArry.Add("24000");

                var accuracyArry = new List<string>();//精度
                accuracyArry.Add("0.05");
                accuracyArry.Add("0.015");

                var processTypeArry = new List<string>();//加工类型
                processTypeArry.Add("精加工");
                processTypeArry.Add("粗加啊");
                processTypeArry.Add("半精加工");//粗加工，半精加工，模架加工
                processTypeArry.Add("模架加工");
                processTypeArry.Add("电极加工");
                var materialArry = new List<string>();//材料
                materialArry.Add("石墨");
                materialArry.Add("钢料");
                materialArry.Add("铜件");
                materialArry.Add("铝件");
                var handleTypeArry = new List<string>();//刀柄类型
                handleTypeArry.Add("BT40");
                handleTypeArry.Add("A63");
                handleTypeArry.Add("BT30");
                var weightKGArry = new List<string>();//重量



                var pLAN_WORK = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.Order_Id == pLAN_WORK_ORDER.Order_Id);
                var tools = repository.Find<EQU_TOOL>(t => t.Identifier == pLAN_WORK_ORDER.OrderCode);
                var equ = await repository.FindAsyncFirst<EQU_EQUIPMENT>(t => t.Description == pLAN_WORK.processing_machines && t.EquipmentNo != null);


                if (speedArry.Contains(((int)pLAN_WORK.RotationalSpeed.Value).ToString()) == false && pLAN_WORK.RotationalSpeed != null)
                {
                    desc = $"转速{pLAN_WORK.RotationalSpeed.Value}不在范围内！";
                    webResponse.Data = $"转速{pLAN_WORK.RotationalSpeed.Value}不在范围内！";
                    goto endOfLoops;

                }
                if (accuracyArry.Contains(string.IsNullOrEmpty(pLAN_WORK.process_precision) ? "" : pLAN_WORK.process_precision.ToString()) == false || pLAN_WORK.process_precision == null)
                {
                    desc = $"精度{pLAN_WORK.process_precision}不在范围内！";
                    webResponse.Data = $"精度{pLAN_WORK.process_precision}不在范围内！";
                    goto endOfLoops;

                }
                if (processTypeArry.Contains(pLAN_WORK.process_type) == false && pLAN_WORK.process_type == null)
                {
                    desc = $"加工类型{pLAN_WORK.process_type}不在范围内！";
                    webResponse.Data = $"加工类型{pLAN_WORK.process_type}不在范围内！";
                    goto endOfLoops;
                }
                if (materialArry.Contains(pLAN_WORK.ProcessingMaterial) == false && pLAN_WORK.ProcessingMaterial == null)
                {
                    desc = $"材料{pLAN_WORK.ProcessingMaterial}不在范围内！";
                    webResponse.Data = $"材料{pLAN_WORK.ProcessingMaterial}不在范围内！";
                    goto endOfLoops;
                }
                if (handleTypeArry.Contains(pLAN_WORK.HolderType) == false && pLAN_WORK.HolderType == null)
                {
                    desc = $"刀柄类型{pLAN_WORK.HolderType}不在范围内！";
                    webResponse.Data = $"刀柄类型{pLAN_WORK.HolderType}不在范围内！";
                    goto endOfLoops;
                }



            endOfLoops:
                WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
                {
                    if (pLAN_WORK != null && desc != "")
                    {
                        pLAN_WORK.Description = desc;
                        repository.DbContext.Set<PLAN_WORK_ORDER>().Update(pLAN_WORK);
                        repository.DbContext.SaveChanges();
                    }
                    else
                    {

                        if (equ != null)
                        {
                            // weightKGArry.Add(equ.WeightKG.ToString());
                            foreach (var item in tools)
                            {
                                if (item.reality_R < 0)
                                {
                                    desc = $"实际半径{item.reality_R}不在范围内！";
                                    break;
                                }
                                if (item.reality_R > equ.Max_reality_R)
                                {
                                    desc = $"实际半径{item.reality_R}不在范围内！";
                                    break;
                                }
                            }
                        }

                        if (desc == "")
                        {
                            desc = "排产下发前检查通过";
                        }
                        pLAN_WORK.Description = desc;
                        repository.DbContext.Set<PLAN_WORK_ORDER>().Update(pLAN_WORK);
                        repository.DbContext.SaveChanges();
                    }
                    return webResponse.OK(ResponseType.Success);
                });

                //Logger.Info(LoggerType.Success, eQU_EQUIPMENT.Serialize(), webResponse.Message, msg);
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                {
                    throw new Exception(ex.Message + ex.StackTrace);
                }
                Logger.Info(LoggerType.Exception, "", webResponse.Message, msg);
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {

            }
        }
        #region by guoyuguo 2024.12.27 工单检查
        /// <summary>
        /// 逐行读取文件,返回列表
        /// </summary>
        /// <param name="pathAName"></param>
        /// <returns></returns>
        public static List<string> ReadTXT_TextReader(string pathAName)
        {
            List<string> txtContent = new List<string>();
            if (File.Exists(pathAName))
            {
                using (TextReader reader = new StreamReader(pathAName))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null) // 逐行读取文件内容
                    {
                        txtContent.Add(line); // 输出每行内容到控制台
                    }
                }
            }
            return txtContent;
        }
        /// <summary>
        /// 公共方法 检查程序文件 重命名文件
        /// </summary>
        /// <param name="pLAN_WORK_ORDER"></param>
        /// <param name="msg"></param>
        /// <param name="desc"></param>
        /// <param name="pLAN_WORK"></param>
        /// <param name="eQU_EQUIPMENT"></param>
        /// <param name="path"></param>
        /// <param name="numberStr"></param>
        /// <returns></returns>
        private bool CheckCNCFileRenameFile(PLAN_WORK_ORDER pLAN_WORK_ORDER,  string msg,out string fileSize, out string desc, PLAN_WORK_ORDER pLAN_WORK, EQU_EQUIPMENT eQU_EQUIPMENT,  string path,string numberStr)
        {
            int lineCount = 0;
            desc = string.Empty;
            fileSize = string.Empty;
            bool endOfLoop = false;
            var filePathCNC = Path.Combine(path, eQU_EQUIPMENT.name + "\\" + pLAN_WORK_ORDER.work_order_number + "\\" + numberStr + ".CNC");
            var filePathCN= Path.Combine(path, eQU_EQUIPMENT.name + "\\" + pLAN_WORK_ORDER.work_order_number + "\\" + numberStr + ".CN");
            if(File.Exists(filePathCN))
            {
                File.Move(filePathCN, filePathCNC);
            }
            // 处理每个文件
            FileInfo fileInfo = new FileInfo(filePathCNC);
            string formattedSize = FormatFileSize(fileInfo.Length);            
            lineCount = CountLinesWithEmptyCheck(filePathCNC);
            fileSize =formattedSize+ lineCount+"行";            
            if (!File.Exists(filePathCNC) && !File.Exists(filePathCNC))
            {
                desc = $"程序文件{numberStr + ".CNC"}不存在！";
                webResponse.Data = $"程序文件{numberStr + ".CNC"}不存在！";
                Logger.Info(LoggerType.Exception, $"程序文件{numberStr + ".CNC"}不存在！", webResponse.Data.ToString(), msg);
                endOfLoop = true;
            }

            return endOfLoop;
        }
        /// <summary>
        /// 工单检查
        /// </summary>
        /// <param name="pLAN_WORK_ORDER"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<WebResponseContent> OrderCheck(PLAN_WORK_ORDER pLAN_WORK_ORDER)
        {
            string msg = string.Empty;
            string desc = string.Empty;
            string fileSize = string.Empty;
            try
            {
                //1.程序文件确认
                var pLAN_WORK = await repository.FindAsyncFirst<PLAN_WORK_ORDER>(t => t.Order_Id == pLAN_WORK_ORDER.Order_Id);
                var programs = await repository.FindAsync<PROC_PROGRAM>(t => t.Identifier == pLAN_WORK.OrderCode);
                var tools = await repository.FindAsync<EQU_TOOL>(t => t.Identifier == pLAN_WORK_ORDER.OrderCode);
                var eQU_EQUIPMENT = await repository.FindAsyncFirst<EQU_EQUIPMENT>(t => t.Description == pLAN_WORK.processing_machines);
                var fTP_Remote_Path = QueryInteConfigure("FTP_Remote_Path");
                if (fTP_Remote_Path != null)
                {
                    var physicalProvider = new PhysicalFileProvider(fTP_Remote_Path.ConfigureParam);//("C:\\FTP_Remote_Path");
                    var pathBase = ((PhysicalFileProvider)physicalProvider).Root;
                    var path = ((PhysicalFileProvider)physicalProvider).Root;
                    var orderCheck = QueryInteConfigure("OrderCheck");
                    if (orderCheck == null)
                    {
                        desc = $"OrderCheck无配置";
                        Logger.Info(LoggerType.Exception, "OrderCheck无配置", webResponse.Message, msg);
                        return webResponse.Error(ResponseType.ServerError);
                    }
                    // //measure_number,centring_number,make_level_number  测量 分中 找平
                    if (pLAN_WORK.processing_machines == "4号机")
                    { goto endOfLoops; }
                    else if (pLAN_WORK.processing_machines != "3号机")
                    {
                        if (pLAN_WORK.measure_number != null)
                        {
                            if (CheckCNCFileRenameFile(pLAN_WORK_ORDER, msg,out fileSize, out desc, pLAN_WORK, eQU_EQUIPMENT, path, pLAN_WORK.measure_number))
                            {
                                goto endOfLoops;
                            }
                        }
                        if (pLAN_WORK.centring_number != null)
                        {
                            if (CheckCNCFileRenameFile(pLAN_WORK_ORDER, msg,out  fileSize, out desc, pLAN_WORK, eQU_EQUIPMENT, path, pLAN_WORK.centring_number))
                            {
                                goto endOfLoops;
                            }
                        }
                        if (pLAN_WORK.make_level_number != null)
                        {
                            if (CheckCNCFileRenameFile(pLAN_WORK_ORDER, msg,out fileSize, out desc, pLAN_WORK, eQU_EQUIPMENT, path, pLAN_WORK.make_level_number))
                            {
                                goto endOfLoops;
                            }
                        }
                    }

                    //创建O0995.CNC O0996.CNC O0997.CNC O1000.CNC
                    List<string> strCNC = new List<string>();
                    strCNC.Add("O0995.CNC");
                    strCNC.Add("O0996.CNC");
                    strCNC.Add("O0997.CNC");
                    strCNC.Add("O1000.CNC");
                    foreach (var item in strCNC)
                    {
                        var filePath = Path.Combine(path, eQU_EQUIPMENT.name + "\\" + pLAN_WORK_ORDER.work_order_number + "\\" + item);
                        //string sourceFile = Path.Combine(path, eQU_EQUIPMENT.name + "\\必备文件"+ "\\" + item);// @"C:\path\to\source\file.txt";
                        //string destinationFile = filePath;// @"C:\path\to\destination\file_copy.txt";

                        //if (item == "O0995.CNC"||item== "O0996.CNC"||item== "O0997.CNC"||item== "O1000.CNC")
                        //{
                        //    //StringBuilder str = new StringBuilder();
                        //    //str.AppendLine($"{eQU_EQUIPMENT.Content5}");
                        //    //File.WriteAllText(filePath, eQU_EQUIPMENT.Content5);
                        //    //    try
                        //    //    {
                        //    //        using (FileStream sourceStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read))
                        //    //        {
                        //    //            byte[] buffer = new byte[sourceStream.Length];
                        //    //            int length;
                        //    //            while ((length = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
                        //    //            {
                        //    //                using (FileStream destinationStream = new FileStream(destinationFile, FileMode.Create, FileAccess.Write))
                        //    //                {
                        //    //                    destinationStream.Write(buffer, 0, length);
                        //    //                }
                        //    //            }
                        //    //        }
                        //    //        Console.WriteLine("文件复制成功！");
                        //    //    }
                        //    //    catch (Exception ex)
                        //    //    {
                        //    //        Logger.Info(LoggerType.Exception, item+"文件复制失败", webResponse.Message, ex.Message);
                        //    //        return webResponse.Error(ResponseType.ServerError);

                        //    //    }
                        //}
                        using (StreamWriter writer = new StreamWriter(filePath))
                        {
                            StringBuilder str = new StringBuilder();
                            if (item == "O0995.CNC")
                            {
                                str.AppendLine($"{eQU_EQUIPMENT.Content5}");
                                str.Replace("\n", "\r\n");
                                writer.WriteLine(str.ToString()); // 写入内容并换行
                                                                  //  File.WriteAllText("users.txt", str.ToString());
                            }
                            if (item == "O0996.CNC")
                            {
                                str.AppendLine($"{eQU_EQUIPMENT.Content5}");
                                str.Replace("\n", "\r\n");
                                writer.WriteLine(eQU_EQUIPMENT.Context6); // 写入内容并换行
                            }
                            if (item == "O0997.CNC")
                            {
                                str.AppendLine($"{eQU_EQUIPMENT.Content5}");
                                str.Replace("\n", "\r\n");
                                writer.WriteLine(eQU_EQUIPMENT.Context7); // 写入内容并换行
                            }
                            if (item == "O1000.CNC")
                            {
                                str.AppendLine($"{eQU_EQUIPMENT.Content5}");
                                str.Replace("\n", "\r\n");
                                writer.WriteLine(eQU_EQUIPMENT.Content1000); // 写入内容并换行
                            }
                        }
                    }
                    var arryCheck = orderCheck.ConfigureParam.Split(",");
                    foreach (var program in programs)
                    {
                        var toolOne = tools.Where(t => t.Identifier == program.Identifier && t.program_seq == program.sequence).FirstOrDefault();
                        if (CheckCNCFileRenameFile(pLAN_WORK_ORDER, msg,out fileSize, out desc, pLAN_WORK, eQU_EQUIPMENT, path, program.program_name))
                        {
                            goto endOfLoops;
                        }
                        if(toolOne!=null)
                        {
                            toolOne.FileSize= fileSize;
                        }
                        var filePath = Path.Combine(path, eQU_EQUIPMENT.name + "\\" + pLAN_WORK_ORDER.work_order_number + "\\" + program.program_name + ".CNC");
                      
                        var listr = ReadTXT_TextReader(filePath);
                        foreach (var item in arryCheck)
                        {
                            var num = listr.Where(t => t.Contains(item)).Count();
                            if (num > 0)
                            {
                                desc = $"程序文件{program.program_name + ".CNC"}中{item}已存在！请确认";
                                webResponse.Data = $"程序文件{program.program_name + ".CNC"}中{item}已存在！请确认";
                                Logger.Info(LoggerType.Exception, $"程序文件{program.program_name + ".CNC"}中{item}已存在！请确认", webResponse.Data.ToString(), msg);

                                goto endOfLoops;

                            }
                        }
                        //程序文件中是否存在程序名
                        var num1 = listr.Where(t => t.Contains(program.program_name)).Count();
                        if (num1 == 0)
                        {
                            desc = $"程序文件{program.program_name + ".CNC"}中程序名{program.program_name}不存在！请确认";
                            webResponse.Data = $"程序文件{program.program_name + ".CNC"}中程序名{program.program_name}不存在！请确认";
                            Logger.Info(LoggerType.Exception, $"程序文件{program.program_name + ".CNC"}中程序名{program.program_name}不存在！请确认", webResponse.Data.ToString(), msg);

                            goto endOfLoops;

                        }

                    }
                }

            endOfLoops:
                WebResponseContent webResponse1 = repository.DbContextBeginTransaction(() =>
                {
                    repository.DbContext.Set<EQU_TOOL>().UpdateRange(tools);
                    if (pLAN_WORK != null && desc != "")
                    {
                        pLAN_WORK.Description = desc;
                        repository.DbContext.Set<PLAN_WORK_ORDER>().Update(pLAN_WORK);
                        repository.DbContext.SaveChanges();
                    }
                    else
                    {
                        desc = "工单下发前检查通过";
                        pLAN_WORK.Description = desc;
                        repository.DbContext.Set<PLAN_WORK_ORDER>().Update(pLAN_WORK);
                        repository.DbContext.SaveChanges();
                    }
                    return webResponse.OK(ResponseType.Success);
                });

                //Logger.Info(LoggerType.Success, eQU_EQUIPMENT.Serialize(), webResponse.Message, msg);
                return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;
                if (_context.GetService<Microsoft.AspNetCore.Hosting.IWebHostEnvironment>().IsDevelopment())
                {
                    throw new Exception(ex.Message + ex.StackTrace);
                }
                Logger.Info(LoggerType.Exception, "", webResponse.Message, msg);
                return webResponse.Error(ResponseType.ServerError);
            }
            finally
            {

            }
        }


        static string FormatFileSize(long bytes)
        {
            string[] units = { "B", "KB", "MB", "GB", "TB" };
            int unitIndex = 0;
            double size = bytes;

            while (size >= 1024 && unitIndex < units.Length - 1)
            {
                size /= 1024;
                unitIndex++;
            }

            return $"{size:0.##} {units[unitIndex]}";
        }
        static int CountLinesWithStreamReader(string filePath)
        {
            int count = 0;
            using (var reader = new StreamReader(filePath))
            {
                while (reader.ReadLine() != null) count++;
            }
            return count;
        }

        static int CountLinesWithEmptyCheck(string filePath)
        {
            int count = 0;
            using (var reader = new StreamReader(filePath))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    if (!string.IsNullOrWhiteSpace(line)) count++;
                }
            }
            return count;
        }

        #endregion
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public async Task<WebResponseContent> SendEmail()
        {
            try
            {

                var faultMail = QueryInteConfigure("FaultMail");
                if (faultMail == null)
                {
                    Logger.Info(LoggerType.Exception, "FaultMail无配置", webResponse.Message, "FaultMail无配置");
                    return webResponse.Error(ResponseType.ServerError);
                }
                var senderPasswords = QueryInteConfigure("SenderPassword");
                if (senderPasswords == null)
                {
                    //  desc = $"FaultMail无配置";
                    Logger.Info(LoggerType.Exception, "SenderPassword无配置", webResponse.Message, "SenderPassword无配置");
                    return webResponse.Error(ResponseType.ServerError);
                }
                var sendEmailTimeInterval = QueryInteConfigure("SendEmailTimeInterval");

                if (sendEmailTimeInterval == null)
                {
                    Logger.Info(LoggerType.Exception, "SendEmailTimeInterval无配置", webResponse.Message, "SendEmailTimeInterval无配置");
                    return webResponse.Error(ResponseType.ServerError);
                }
                var timeInterval = int.Parse(sendEmailTimeInterval.ConfigureParam);

                // 设置发送者的电子邮件地址和密码
                string senderEmail = "278836453@qq.com";
                string senderPassword = senderPasswords.ConfigureParam;
                var arryMails = faultMail.ConfigureParam.Split(",");
                var eQU_FAULT_PHENOMENON = await repository.FindAsyncFirst<EQU_FAULT_PHENOMENON>(t => t.IsSend != "1" && t.CreateOn > DateTime.Now.AddMinutes(-timeInterval));
                if (eQU_FAULT_PHENOMENON == null)
                {
                    //  Logger.Info(LoggerType.Exception, "没有需要发送的邮件", webResponse.Message, "没有需要发送的邮件");
                    webResponse.Message = "没有需要发送的邮件";

                    return webResponse.Error(webResponse.Message);
                }
                foreach (var item in arryMails)
                {
                    // 设置收件人的电子邮件地址
                    string receiverEmail = item;
                    // 创建邮件对象
                    MailMessage mail = new MailMessage(senderEmail, receiverEmail);
                    if (eQU_FAULT_PHENOMENON != null)
                    {
                        //mail.Subject = @"MES " + eQU_FAULT_PHENOMENON.Content;// "MES警告：找平程序执行结果0.023000000000024556大于设定精度0存在异常！";
                        mail.Subject = "MES";
                        mail.Body = "TaskNo:" + eQU_FAULT_PHENOMENON.TaskNo + " " + eQU_FAULT_PHENOMENON.Content + "警告时间:" + eQU_FAULT_PHENOMENON.CreateOn;
                        // 创建SMTP客户端
                        SmtpClient smtpClient = new SmtpClient("smtp.qq.com");
                        smtpClient.Port = 587;
                        smtpClient.Credentials = new NetworkCredential(senderEmail, senderPassword);
                        smtpClient.EnableSsl = true;
                        // 发送邮件
                        smtpClient.Send(mail);
                        eQU_FAULT_PHENOMENON.IsSend = "1";
                        eQU_FAULT_PHENOMENON.SendMail = item;
                        eQU_FAULT_PHENOMENON.LastUpdateOn = DateTime.Now;
                        repository.DbContext.Set<EQU_FAULT_PHENOMENON>().Update(eQU_FAULT_PHENOMENON);
                        repository.DbContext.SaveChanges();
                    }
                }
                Logger.Info(LoggerType.Success, "邮件发送成功", webResponse.Message, "邮件发送成功");

            }
            catch (Exception ex)
            {
                Logger.Info(LoggerType.Exception, "邮件发送失败：" + ex.Message, webResponse.Message, "邮件发送失败：" + ex.Message);
                webResponse.Data = "邮件发送失败：" + ex.Message;
                return webResponse.Error(ResponseType.ServerError);
            }
            return webResponse.OK(ResponseType.Success);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="equ_TASKVM"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>

        public async Task<WebResponseContent> Flow(PROC_PROCESS row)
        {

            string msg = string.Empty;
            try
            {

                List<PROC_PROCESSList> PROC_PROCESSListList = new List<PROC_PROCESSList>();

                PROC_PROCESSListList = await repository.FindAsync<PROC_PROCESSList>(t => t.Process_Id == row.Process_Id);
                var list = PROC_PROCESSListList.OrderBy(t => t.OperationCode).ToList();
                Flow flow = new Flow();
                WebResponseContent webResponseContent = new WebResponseContent();
                flow.nodes = new List<nodes>();
                flow.edges = new List<edges>();
                int inum = 0;
                foreach (var item in list)
                {
                    flow.nodes.Add(new nodes() { id = "1" + inum, text = item.OperationCode, type = "rect", x = 100 + 150 * inum, y = 100 });
                    inum++;
                }
                int ii = 0;

                //foreach (var item in flow.nodes)
                for (int i = 0; i < flow.nodes.Count; i++)
                {
                    if (i == 0)
                    { }
                    else
                    {
                        flow.edges.Add(new edges() { type = "polyline", sourceNodeId = flow.nodes[i - 1].id, targetNodeId = flow.nodes[i].id });
                    }
                }

                //flow.nodes.Add(new nodes() { id = "1", text = "3000", type = "rect", x = 100, y = 100 });
                //flow.nodes.Add(new nodes() { id = "2", text = "4000", type = "rect", x = 300, y = 100 });
                //flow.edges.Add(new edges() { type = "polyline", sourceNodeId = "10", targetNodeId = "11" });
                //flow.edges.Add(new edges() { type = "polyline", sourceNodeId = "11", targetNodeId = "12" });
                string json = JsonConvert.SerializeObject(flow);
                webResponseContent.Data = json;// flow.();

                return webResponseContent;

                //    return webResponse.OK(ResponseType.Success);
            }
            catch (Exception ex)
            {
                msg = ex.Message + ex.StackTrace;

                return webResponse.Error(ResponseType.ServerError);
            }

        }

    }
    
}

